screenshot.py 6.5 KB

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