赞
踩
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pyautogui
from PIL import Image
import cv2
# In[2]:
# 使用pyautogui进行屏幕截图
screenshot = pyautogui.screenshot()
# In[3]:
# 保存屏幕截图和待查找图片
screenshot.save('screenshot.png')
# In[4]:
# 读取目标图片和待查找图片
target = cv2.imread("template.png")
screenshot = cv2.imread("screenshot.png")
# In[5]:
# target = cv2.resize(target, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
# In[6]:
# screenshot = cv2.resize(screenshot, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
# In[7]:
# cv2.imshow("Result", target)
# In[8]:
# cv2.imshow("Result", screenshot)
# In[9]:
# 使用模板匹配方法
result = cv2.matchTemplate(target, screenshot, cv2.TM_CCOEFF_NORMED)
# In[10]:
# result
# 【图片匹配】这个功能非常有趣,让pyautogui模块有了灵魂。学习pyautogui主要是用此功能。
# PyAutoGUI的图片匹配功能,它是在屏幕按像素匹配,定位图片在屏幕上的坐标位置,locateOnScreen()函数返回region对象,即左上角坐标、宽度、高度4个值组成的元组,再用center()函数计算出中心坐标,locateCenterOnScreen()函数则一步到位,返回中心坐标。如果把需要点击的菜单、按钮事先保存成图片,可以用来自动查找菜单、按钮位置,再交由click()函数控制鼠标去点击。
# 找弹框的【关闭】按钮
# close_icon = os.path.join('img', 'target', 'close.png')
# left, up, width, height = pyautogui.locateOnWindow(close_icon, confidence=0.8)
# print(left, up, width, height)
# # 移动到【关闭】按钮处
# pyautogui.moveTo(left, up, duration=1)
# # 点击【关闭】按钮
# pyautogui.click()
# 上面left, up, width, height = pyautogui.locateOnWindow(close_icon, confidence=0.8)指定了confidence=0.8 即置信度(匹配度)80%即可认为找到了。
# 默认情况下,上面代码报错,提示让安装opencv:
# pip install opencv-python
# In[11]:
# 找到最佳匹配位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# In[12]:
# min_val
# In[13]:
# max_val
# In[14]:
# min_loc
# In[15]:
max_loc
# In[16]:
top_left = max_loc
bottom_right = (top_left[0] + target.shape[1], top_left[1] + target.shape[0])
# In[17]:
bottom_right
# In[18]:
import pyautogui
# 获取屏幕尺寸
screen_width, screen_height = pyautogui.size()
# In[19]:
# 移动鼠标到指定位置 , /2 是为了移动到图片正中心
x_pos = (top_left[0] + bottom_right[0])/2
y_pos = (top_left[1] + bottom_right[1])/2
# 以 左上角为原点(0,0),向右为+X,下向下为+Y,
pyautogui.moveTo(x_pos, y_pos)
# In[ ]:
# 在当前位置进行点击
pyautogui.click()
# 在指定位置(x=100, y=100)进行点击
# pyautogui.click(x=100, y=100)
# 在指定位置(x=100, y=100)进行双击
# pyautogui.doubleClick(x=100, y=100)
# 在指定位置(x=100, y=100)进行右键点击
# pyautogui.rightClick(x=100, y=100)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。