screenshot.py 6.1 KB

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