请根据刚才的报错,改良以下代码:import cv2 import numpy as np from pynput.mouse import Button, Controller from PIL import ImageGrab # 读取目标图片 target_img = cv2.imread("baidu.png", cv2.IMREAD_GRAYSCALE) # 创建一个Controller对象 mouse = Controller() # 获取屏幕截图 screenshot = ImageGrab.grab() # 将截图转换为numpy数组 screen = np.array(screenshot) # 保存截图为screen.png screenshot.save('screen.png') # 在屏幕上搜索目标图片 result = cv2.matchTemplate(screen, target_img, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) top_left = max_loc h, w = target_img.shape[:2] bottom_right = (top_left[0] + w, top_left[1] + h) # 模拟鼠标点击目标图片的位置 mouse.position = (top_left[0] + w//2, top_left[1] + h//2) mouse.press(Button.left) mouse.release(Button.left) time.sleep(2)
时间: 2024-04-25 22:27:12 浏览: 126
import cv2 import numpy as np from pynput.mouse import Button, Controller from PIL import ImageGrab import time
读取目标图片
target_img = cv2.imread("baidu.png", cv2.IMREAD_GRAYSCALE)
创建一个Controller对象
mouse = Controller()
获取屏幕截图
screenshot = ImageGrab.grab()
将截图转换为numpy数组
screen = np.array(screenshot)
保存截图为screen.png
screenshot.save('screen.png')
在屏幕上搜索目标图片
result = cv2.matchTemplate(screen, target_img, cv2.TM_CCOEFF_NORMED)
获取匹配结果的坐标
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) top_left = max_loc h, w = target_img.shape[:2] bottom_right = (top_left[0] + w, top_left[1] + h)
模拟鼠标点击目标图片的位置
mouse.position = (top_left[0] + w//2, top_left[1] + h//2) mouse.press(Button.left) mouse.release(Button.left)
time.sleep(2)