screenshot.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import cv2
  2. import time
  3. import datetime
  4. import numpy as np
  5. import io
  6. from PIL import Image
  7. from io import BytesIO
  8. from ppadb.client import Client as AdbClient
  9. from PIL import Image
  10. client = AdbClient(host="127.0.0.1", port=5037)
  11. device = client.device("192.168.178.32:5555")
  12. # template positions
  13. close_sub_fights = cv2.imread('templates/close_sub_fights.jpg')
  14. close_fight = cv2.imread('templates/close_fight.jpg')
  15. fight_button = cv2.imread('templates/i.jpg')
  16. end_of_log = cv2.imread('templates/end_of_log.jpg')
  17. # cursor positions
  18. fight_scroll_top = "2494 626"
  19. fight_scroll_bottom = "2200 1520"
  20. titan_fight = "1400 860"
  21. damage_taken = "450 850"
  22. close_details = "2175 450"
  23. close_titan_fight = "2650 570"
  24. def non_max_suppression(boxes, overlapThresh):
  25. if len(boxes) == 0:
  26. return []
  27. # Convert to float
  28. boxes = np.array(boxes, dtype="float")
  29. # Initialize the list of picked indexes
  30. pick = []
  31. # Grab the coordinates of the bounding boxes
  32. x1 = boxes[:,0]
  33. y1 = boxes[:,1]
  34. x2 = boxes[:,2]
  35. y2 = boxes[:,3]
  36. # Compute the area of the bounding boxes and sort by bottom-right y-coordinate
  37. area = (x2 - x1 + 1) * (y2 - y1 + 1)
  38. idxs = np.argsort(y2)
  39. # Keep looping while some indexes still remain in the indexes list
  40. while len(idxs) > 0:
  41. # Grab the last index in the indexes list and add the index value to the list of picked indexes
  42. last = len(idxs) - 1
  43. i = idxs[last]
  44. pick.append(i)
  45. # Find the largest (x, y) coordinates for the start of the bounding box and the smallest (x, y)
  46. # coordinates for the end of the bounding box
  47. xx1 = np.maximum(x1[i], x1[idxs[:last]])
  48. yy1 = np.maximum(y1[i], y1[idxs[:last]])
  49. xx2 = np.minimum(x2[i], x2[idxs[:last]])
  50. yy2 = np.minimum(y2[i], y2[idxs[:last]])
  51. # Compute the width and height of the bounding box
  52. w = np.maximum(0, xx2 - xx1 + 1)
  53. h = np.maximum(0, yy2 - yy1 + 1)
  54. # Compute the ratio of overlap
  55. overlap = (w * h) / area[idxs[:last]]
  56. # Delete all indexes from the index list that have overlap greater than the threshold
  57. idxs = np.delete(idxs, np.concatenate(([last], np.where(overlap > overlapThresh)[0])))
  58. # Return only the bounding boxes that were picked
  59. return boxes[pick].astype("int")
  60. def screen_has_changed(prev_screenshot, threshold=0.01):
  61. # Take a new screenshot
  62. current_screenshot = device.screencap()
  63. # Convert to NumPy arrays
  64. prev_img = np.frombuffer(prev_screenshot, dtype=np.uint8)
  65. current_img = np.frombuffer(current_screenshot, dtype=np.uint8)
  66. # Load images
  67. prev_img = cv2.imdecode(prev_img, cv2.IMREAD_COLOR)
  68. current_img = cv2.imdecode(current_img, cv2.IMREAD_COLOR)
  69. # Calculate absolute difference
  70. diff = cv2.absdiff(prev_img, current_img)
  71. non_zero_count = np.count_nonzero(diff)
  72. # print(f"diff: {non_zero_count} > {threshold * diff.size} = {non_zero_count > threshold * diff.size}")
  73. # Check if the difference is greater than the threshold
  74. return non_zero_count > threshold * diff.size
  75. def save_screenshot():
  76. # Take a screenshot
  77. result = device.screencap()
  78. timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  79. image = Image.open(io.BytesIO(result))
  80. jpeg_filename = f"/mnt/t/nextcloud/InstantUpload/Herowars/{timestamp}.jpg"
  81. image = image.convert('RGB') # Convert to RGB mode for JPEG
  82. with open(jpeg_filename, "wb") as fp:
  83. image.save(fp, format='JPEG', quality=85) # Adjust quality as needed
  84. time.sleep(0.5)
  85. def wait_for_screen_change():
  86. # Usage example
  87. prev_screenshot = device.screencap()
  88. while not screen_has_changed(prev_screenshot):
  89. time.sleep(0.1) # Polling interval
  90. def tap(location):
  91. device.shell(f"input tap {location}")
  92. time.sleep(1)
  93. def swipe(start, end):
  94. device.shell(f"input swipe {start} {end} 1000")
  95. time.sleep(0.5)
  96. def tap_button(template):
  97. button = find_templates(template)
  98. if len(button) == 0:
  99. return
  100. tap(f"{button[0][0]} {button[0][1]}")
  101. def is_end_of_log(template):
  102. templates = find_templates(template)
  103. result = len(templates) > 0
  104. if result:
  105. print("reached end of guild war log!")
  106. return result
  107. def find_templates(template_image):
  108. screenshot = device.screencap()
  109. target_image = Image.open(BytesIO(screenshot))
  110. # Convert the image to a NumPy array and then to BGR format (which OpenCV uses)
  111. target_image = np.array(target_image)
  112. target_image = cv2.cvtColor(target_image, cv2.COLOR_RGB2BGR)
  113. w, h = template_image.shape[:-1]
  114. # Template matching
  115. result = cv2.matchTemplate(target_image, template_image, cv2.TM_CCOEFF_NORMED)
  116. # Define a threshold
  117. threshold = 0.9 # Adjust this threshold based on your requirements
  118. # Finding all locations where match exceeds threshold
  119. locations = np.where(result >= threshold)
  120. locations = list(zip(*locations[::-1]))
  121. # Create list of rectangles
  122. rectangles = [(*loc, loc[0] + w, loc[1] + h) for loc in locations]
  123. # Apply non-maximum suppression to remove overlaps
  124. rectangles = non_max_suppression(rectangles, 0.3)
  125. # Initialize an empty list to store coordinates
  126. coordinates = []
  127. for (startX, startY, endX, endY) in rectangles:
  128. # Calculate the center coordinates
  129. centerX = round(startX + (endX - startX) / 2)
  130. centerY = round(startY + (endY - startY) / 2)
  131. # Append the coordinate pair to the list
  132. coordinates.append((centerX, centerY))
  133. return coordinates
  134. def find_max_y_pair(coordinates):
  135. # find the coordinate pair with the maximum y value
  136. result = max(coordinates, key=lambda x: x[1])
  137. return f"{result[0]} {result[1]}"
  138. def take_fight_screenshots():
  139. save_screenshot()
  140. tap(damage_taken)
  141. save_screenshot()
  142. tap_button(close_fight)
  143. def process_war_log():
  144. buttons = find_templates(fight_button)
  145. if len(buttons) == 0:
  146. swipe(fight_scroll_bottom, fight_scroll_top)
  147. return
  148. # process all found buttons
  149. for pair in buttons:
  150. tap(f"{pair[0]} {pair[1]}")
  151. sub_buttons = find_templates(fight_button)
  152. if (len(sub_buttons) == 0):
  153. take_fight_screenshots()
  154. else:
  155. for pair2 in sub_buttons:
  156. tap(f"{pair2[0]} {pair2[1]}")
  157. take_fight_screenshots()
  158. tap_button(close_sub_fights)
  159. find_max_y_pair(buttons)
  160. swipe(find_max_y_pair(buttons), fight_scroll_top)
  161. # start
  162. while not is_end_of_log(end_of_log):
  163. process_war_log();
  164. # possible duplicates here, but necessary to be sure to get the last fights
  165. process_war_log();