screenshot.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. # TODO: write screenshots to network folder /mnt/t/nextcloud/InstantUpload/Herowars/
  80. jpeg_filename = f"fights/{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(templates)
  106. print("reached end of guild war log!")
  107. return result
  108. def find_templates(template_image):
  109. screenshot = device.screencap()
  110. target_image = Image.open(BytesIO(screenshot))
  111. # Convert the image to a NumPy array and then to BGR format (which OpenCV uses)
  112. target_image = np.array(target_image)
  113. target_image = cv2.cvtColor(target_image, cv2.COLOR_RGB2BGR)
  114. w, h = template_image.shape[:-1]
  115. # Template matching
  116. result = cv2.matchTemplate(target_image, template_image, cv2.TM_CCOEFF_NORMED)
  117. # Define a threshold
  118. threshold = 0.9 # Adjust this threshold based on your requirements
  119. # Finding all locations where match exceeds threshold
  120. locations = np.where(result >= threshold)
  121. locations = list(zip(*locations[::-1]))
  122. # Create list of rectangles
  123. rectangles = [(*loc, loc[0] + w, loc[1] + h) for loc in locations]
  124. # Apply non-maximum suppression to remove overlaps
  125. rectangles = non_max_suppression(rectangles, 0.3)
  126. # Initialize an empty list to store coordinates
  127. coordinates = []
  128. for (startX, startY, endX, endY) in rectangles:
  129. # Calculate the center coordinates
  130. centerX = round(startX + (endX - startX) / 2)
  131. centerY = round(startY + (endY - startY) / 2)
  132. # Append the coordinate pair to the list
  133. coordinates.append((centerX, centerY))
  134. return coordinates
  135. def find_max_y_pair(coordinates):
  136. # find the coordinate pair with the maximum y value
  137. result = max(coordinates, key=lambda x: x[1])
  138. return f"{result[0]} {result[1]}"
  139. def take_fight_screenshots():
  140. save_screenshot()
  141. tap(damage_taken)
  142. save_screenshot()
  143. tap_button(close_fight)
  144. def process_war_log():
  145. buttons = find_templates(fight_button)
  146. # process all found buttons
  147. for pair in buttons:
  148. tap(f"{pair[0]} {pair[1]}")
  149. sub_buttons = find_templates(fight_button)
  150. if (len(sub_buttons) == 0):
  151. take_fight_screenshots()
  152. else:
  153. for pair2 in sub_buttons:
  154. tap(f"{pair2[0]} {pair2[1]}")
  155. take_fight_screenshots()
  156. tap_button(close_sub_fights)
  157. find_max_y_pair(buttons)
  158. swipe(find_max_y_pair(buttons), fight_scroll_top)
  159. # start
  160. while True:
  161. process_war_log();
  162. if is_end_of_log(end_of_log):
  163. break;