python实现一个功能,截图并识别目标图片的位置,点击目标图片的位置
时间: 2024-03-11 18:50:42 浏览: 14
下面是实现截图并识别目标图片位置,并模拟鼠标点击目标图片的位置的Python代码:
```python
import cv2
import numpy as np
from pynput.mouse import Button, Controller
from PIL import ImageGrab
import time
# 定义目标图片路径和阈值
target_img_path = "target.png"
threshold = 0.8
# 读取目标图片
target_img = cv2.imread(target_img_path, cv2.IMREAD_GRAYSCALE)
# 创建一个Controller对象
mouse = Controller()
while True:
# 获取屏幕截图
screenshot = ImageGrab.grab()
# 将截图转换为numpy数组
screen = np.array(screenshot)
# 在屏幕上搜索目标图片
result = cv2.matchTemplate(screen, target_img, cv2.TM_CCOEFF_NORMED)
# 获取匹配结果的坐标
loc = np.where(result >= threshold)
if len(loc[0]) > 0:
top_left = (loc[1][0], loc[0][0])
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)
```
在上面的代码中,我们通过不断截图并在屏幕上搜索目标图片,如果匹配结果的坐标不为空,则模拟鼠标点击目标图片的位置。这个程序会一直运行,直到我们手动停止它。