# 导入模块 cv2匹配算法 plt 显示图片
import cv2
from matplotlib import pyplot as plt
import pyautogui
import time
# 读入图片 big1.png是背景大图; small.png是需要寻找的小图(格式.jpg .png都行)
# time.sleep(3)
# pyautogui.screenshot('bg.png')
# img = cv2.imread("bg.png",0) # 0 读入灰度图
# img3 = cv2.imread("bg.png",1) # 1 读入彩色图
# img2 = img.copy()
# template = cv2.imread("entry.png",0)
# w, h = template.shape[::-1]
# 6种算法的列表
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
methods = ['cv2.TM_CCOEFF_NORMED']
def find_img(big_path, small_path, method='cv2.TM_CCOEFF_NORMED'):
# Load images
small = cv2.imread(small_path, 0)
big = cv2.imread(big_path, 0)
# Check if images are loaded
if small is None:
raise FileNotFoundError(f"Could not load image at {small_path}")
if big is None:
raise FileNotFoundError(f"Could not load image at {big_path}")
# Get the dimensions of the small image
w, h = small.shape[::-1]
# Apply template matching with the given method
method = eval(method)
res = cv2.matchTemplate(big, small, method)
# Find the location with the best match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
center = ((top_left[0] + bottom_right[0]) // 2, (top_left[1] + bottom_right[1]) // 2)
return center
if __name__ == "__main__":
time.sleep(3)
pyautogui.screenshot('bg.png')
small_path = 'entry.png'
big_path = 'bg.png'
p = find_img(big_path,small_path)
pyautogui.click(p)
No comments:
Post a Comment