imgFind.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # -*- coding: utf-8 -*-
  2. import pyautogui
  3. import random
  4. import time
  5. import numpy as np
  6. import cv2
  7. from PIL import Image
  8. import pyscreeze
  9. pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION = False
  10. g_isDown = False
  11. def set_isDown(value):
  12. global g_isDown
  13. g_isDown = value
  14. def color_string_to_rgb(color_string):
  15. r = int(color_string[0:2], 16)
  16. g = int(color_string[2:4], 16)
  17. b = int(color_string[4:6], 16)
  18. return (r, g, b)
  19. def savePic(screenshot, fileName):
  20. image = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')
  21. image.save(fileName) # 保存为PNG格式的图像文件
  22. def find_center_point(pointArr):
  23. min_distance = float('inf')
  24. center_point = None
  25. for point in pointArr:
  26. total_distance = 0
  27. for other_point in pointArr:
  28. distance = ((other_point[0] - point[0]) ** 2 + (other_point[1] - point[1]) ** 2) ** 0.5
  29. total_distance += distance
  30. if total_distance < min_distance:
  31. min_distance = total_distance
  32. center_point = point
  33. return center_point
  34. class pcacc_img:
  35. def __init__(specifically):
  36. random.seed()
  37. @staticmethod
  38. def find_maxColor_position(cur_region, colorArr): #(left, top, width, height)
  39. left = cur_region[0]
  40. top = cur_region[1]
  41. width = cur_region[2]
  42. height = cur_region[3]
  43. region = (left, top, width, height)
  44. # 目标颜色和容差值
  45. tolerance = 10 # 容差值
  46. # 在指定区域获取屏幕图像
  47. screenshotSrc = pyautogui.screenshot(region=region)
  48. print(region)
  49. screenshot = np.array(screenshotSrc)
  50. dstPointArr = []
  51. # 创建颜色范围的上下界
  52. for color_str in colorArr:
  53. target_color = color_string_to_rgb(color_str)
  54. lower_color = np.array(target_color) - tolerance
  55. upper_color = np.array(target_color) + tolerance
  56. # 在图像中查找匹配的像素
  57. mask = cv2.inRange(screenshot, lower_color, upper_color)
  58. # 显示 mask 图像
  59. #plt.imshow(mask, cmap='gray')
  60. #plt.show()
  61. points = np.transpose(np.where(mask > 0))
  62. if len(points) < 5:
  63. continue
  64. # 转换坐标到全局坐标系
  65. points[:, 0] += region[0]
  66. points[:, 1] += region[1]
  67. '''
  68. # 使用K-means聚类将匹配点分为不同的簇
  69. n_clusters = 5 # 簇的数量,可根据需要进行调整
  70. kmeans = KMeans(n_clusters=n_clusters)
  71. kmeans.fit(points)
  72. # 找到最大的簇
  73. max_cluster_label = np.argmax(np.bincount(kmeans.labels_))
  74. max_cluster_points = points[kmeans.labels_ == max_cluster_label]
  75. '''
  76. # 输出最集中的像素区域的位置
  77. for point in points:
  78. dstPointArr.append(point)
  79. if len(dstPointArr) > 0:
  80. return True, find_center_point(dstPointArr)
  81. else:
  82. return False, (-1, -1)
  83. @staticmethod
  84. def find_img_position(image_path):
  85. # 设置查找的置信度(confidence)阈值,范围从0到1,默认为0.999
  86. confidence_threshold = 0.85
  87. # 查找模糊图片在屏幕上的位置
  88. position = pyautogui.locateOnScreen(image_path, confidence=confidence_threshold)
  89. if position is not None:
  90. return True, position
  91. else:
  92. return False, None
  93. @staticmethod
  94. def choose_two_point_from_position(position):
  95. dst_x1 = random.randint(position.left, position.left + position.width)
  96. dst_y1 = random.randint(position.top, position.top + position.height)
  97. dst_x2 = random.randint(position.left, position.left + position.width)
  98. dst_y2 = random.randint(position.top, position.top + position.height)
  99. return (dst_x1, dst_y1), (dst_x2, dst_y2)
  100. @staticmethod
  101. def choose_one_point_from_position(position):
  102. dst_x1 = random.randint(position.left, position.left + position.width)
  103. dst_y1 = random.randint(position.top, position.top + position.height)
  104. return (dst_x1, dst_y1)
  105. @staticmethod
  106. def find_all_img(image_path):
  107. # 设置查找的置信度(confidence)阈值,范围从0到1,默认为0.999
  108. confidence_threshold = 0.95
  109. # 查找模糊图片在屏幕上的位置
  110. positions = pyautogui.locateAllOnScreen(image_path, confidence=confidence_threshold)
  111. if len(positions) == 0:
  112. return False, []
  113. return True, positions
  114. @staticmethod
  115. def find_img_cv(image_path, region=None, search_order='bottom-up'):
  116. """
  117. 改进版的模板匹配函数,支持从下往上搜索
  118. :param image_path: 模板图片路径
  119. :param region: 截图区域 (left, top, width, height)
  120. :param search_order: 搜索顺序 ('top-down'或'bottom-up')
  121. :return: (是否找到, 随机点坐标)
  122. """
  123. # 读取模板和屏幕截图
  124. confidence_threshold = 0.95
  125. template = cv2.imread(image_path, cv2.IMREAD_COLOR)
  126. screenshot = cv2.cvtColor(np.array(pyautogui.screenshot(region=region)), cv2.COLOR_RGB2BGR)
  127. # 模板匹配
  128. result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
  129. width, height = template.shape[1], template.shape[0]
  130. # 获取所有匹配位置[3,5](@ref)
  131. loc = np.where(result >= confidence_threshold)
  132. matches = list(zip(*loc[::-1])) # 转换为(x,y)坐标列表
  133. if len(matches) == 0:
  134. return False, (-1, -1)
  135. # 根据搜索顺序排序匹配结果[7](@ref)
  136. if search_order == 'bottom-up':
  137. # 从下往上排序:先按y坐标降序,再按x坐标升序
  138. matches.sort(key=lambda m: (-m[1], m[0]))
  139. else: # 默认从上往下
  140. matches.sort(key=lambda m: (m[1], m[0]))
  141. # 选择第一个匹配结果(根据搜索顺序)
  142. left, top = matches[0]
  143. # 计算中间区域(避免点击边缘)
  144. mid_left = int(left + width / 4)
  145. mid_right = int(left + width / 4 * 3)
  146. mid_top = int(top + height / 4)
  147. mid_bottom = int(top + height / 4 * 3)
  148. # 生成随机点击位置
  149. want_x = random.randint(mid_left, mid_right)
  150. want_y = random.randint(mid_top, mid_bottom)
  151. # 添加随机偏移(避免每次都点击相同位置)
  152. dst_x = random.randint(int(want_x - width / 3), int(want_x + width / 3))
  153. dst_y = random.randint(int(want_y - height / 3), int(want_y + height / 3))
  154. print(f"{image_path}:({dst_x}, {dst_y}) [搜索顺序: {search_order}]")
  155. return True, (dst_x, dst_y)
  156. @staticmethod
  157. def find_img_origin(image_path):
  158. # 设置查找的置信度(confidence)阈值,范围从0到1,默认为0.999
  159. confidence_threshold = 0.95
  160. # 查找模糊图片在屏幕上的位置
  161. position = pyautogui.locateOnScreen(image_path, confidence=confidence_threshold)
  162. if position is not None:
  163. #dst_position
  164. dst_x = position.left
  165. dst_y = position.top
  166. print(f"{image_path} origin:({dst_x}, {dst_y})")
  167. return True, (dst_x, dst_y)
  168. else:
  169. return False, (-1, -1)
  170. def find_img_down(image_path):
  171. # 设置查找的置信度(confidence)阈值,范围从0到1,默认为0.999
  172. confidence_threshold = 0.95
  173. # 查找模糊图片在屏幕上的位置
  174. positionAll = pyautogui.locateAllOnScreen(image_path, confidence=confidence_threshold)
  175. location_list = list(positionAll)
  176. localtion_sort = sorted(location_list, key=lambda x: x.top, reverse=True)
  177. if len(localtion_sort) == 0:
  178. return False, (-1, -1)
  179. position = localtion_sort[0]
  180. if position is not None:
  181. # 图片找到了,获取图片的中心点坐标
  182. #mid
  183. mid_left = int(position.left + position.width / 4)
  184. mid_right = int(position.left + position.width / 4 * 3)
  185. mid_top = int(position.top + position.height / 4)
  186. mid_bottom = int(position.top + position.height / 4 * 3)
  187. #want_position
  188. want_x = random.randint(mid_left, mid_right)
  189. want_y = random.randint(mid_top, mid_bottom)
  190. #dst_position
  191. dst_x = random.randint(int(want_x - position.width / 3), int(want_x + position.width / 3))
  192. dst_y = random.randint(int(want_y - position.height / 3), int(want_y + position.height / 3))
  193. print(f"down {image_path}:({dst_x}, {dst_y})")
  194. return True, (dst_x, dst_y)
  195. else:
  196. return False, (-1, -1)
  197. def find_img(image_path):
  198. # 设置查找的置信度(confidence)阈值,范围从0到1,默认为0.999
  199. confidence_threshold = 0.92
  200. # 查找模糊图片在屏幕上的位置
  201. position = pyautogui.locateOnScreen(image_path, confidence=confidence_threshold)
  202. if position is not None:
  203. # 图片找到了,获取图片的中心点坐标
  204. #mid
  205. mid_left = int(position.left + position.width / 4)
  206. mid_right = int(position.left + position.width / 4 * 3)
  207. mid_top = int(position.top + position.height / 4)
  208. mid_bottom = int(position.top + position.height / 4 * 3)
  209. #want_position
  210. want_x = random.randint(mid_left, mid_right)
  211. want_y = random.randint(mid_top, mid_bottom)
  212. #dst_position
  213. dst_x = random.randint(int(want_x - position.width / 3), int(want_x + position.width / 3))
  214. dst_y = random.randint(int(want_y - position.height / 3), int(want_y + position.height / 3))
  215. print(f"{image_path}:({dst_x}, {dst_y})")
  216. return True, (dst_x, dst_y)
  217. else:
  218. return False, (-1, -1)
  219. @staticmethod
  220. def find_imgArr(imgArr):
  221. global g_isDown
  222. for cur_img in imgArr:
  223. if g_isDown:
  224. ret, pos = pcacc_img.find_img_down(cur_img)
  225. else:
  226. ret, pos = pcacc_img.find_img(cur_img)
  227. if ret:
  228. return ret, pos
  229. return False, None
  230. @staticmethod
  231. def find_imgArr_cv(imgArr):
  232. for cur_img in imgArr:
  233. ret, pos = pcacc_img.find_img_cv(cur_img)
  234. if ret:
  235. return ret, pos
  236. return False, None
  237. @staticmethod
  238. def find_imgs(images, is_cv=False):
  239. global g_isDown
  240. if is_cv:
  241. return pcacc_img.find_imgs_cv(images)
  242. else:
  243. if isinstance(images, str):
  244. if g_isDown:
  245. return pcacc_img.find_img_down(images)
  246. else:
  247. return pcacc_img.find_img(images)
  248. elif isinstance(images, (list, tuple)):
  249. return pcacc_img.find_imgArr(images)
  250. else:
  251. raise ValueError("Invalid input type for 'images' parameter.")
  252. @staticmethod
  253. def find_imgs_cv(images):
  254. if isinstance(images, str):
  255. return pcacc_img.find_img_cv(images)
  256. elif isinstance(images, (list, tuple)):
  257. return pcacc_img.find_imgArr_cv(images)
  258. else:
  259. raise ValueError("Invalid input type for 'images' parameter.")
  260. @staticmethod
  261. def find_all_image_locations(image):
  262. confidence_threshold = 0.90
  263. # 查找所有符合条件的图片位置
  264. locations = pyautogui.locateAllOnScreen(image, confidence=confidence_threshold)
  265. # 将位置信息保存到列表中
  266. image_locations = []
  267. for location in locations:
  268. # 获取位置信息的左上角坐标和宽高
  269. x, y, width, height = location
  270. # 将位置信息添加到列表中
  271. image_locations.append((x, y, width, height))
  272. return image_locations
  273. @staticmethod
  274. def find_img_in_area(image,region=None):
  275. confidence_threshold = 0.85
  276. location = pyautogui.locateOnScreen(image,region=region, confidence=confidence_threshold)
  277. if location is not None:
  278. return True
  279. return False
  280. if __name__ == '__main__':
  281. time.sleep(2)
  282. begin = time.time()
  283. pcacc_img.find_maxColor_position((200, 200, 800, 200), {'2EA043'})
  284. cost = time.time() - begin
  285. print("函数执行耗时:", cost, "秒")