python识别图标并点击功能实现
作者:一晌小贪欢
这篇文章主要介绍了python识别图标并点击功能实现,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
python识别图标并点击
首相片帖子已经重复的太多了,我试一下感觉还是很好用的,我就是记录一下 这篇帖子可以直接制作出很多自动点击的工具,甚至是游戏物理辅助工具(因为我就在用)! 视频展示

| 库 | 安装 | 作用 |
|---|---|---|
| pillow | pip install pillow | 加载图片 |
| pyscreeze | pip install pyscreeze | 截屏 |
| pyautogui | pip install pyautogui | 控制鼠标或键盘 |
| opencv-python | pip install opencv-python==4.3.0.38 | 识别匹配图片 |
import time
import pyautogui
import pyscreeze
import cv2
# 屏幕缩放系数 mac缩放是2 windows一般是1
screenScale=1
#事先读取按钮截图
target= cv2.imread(r"./image/ssk.png",cv2.IMREAD_GRAYSCALE)
# 先截图
screenshot=pyscreeze.screenshot('my_screenshot.png')
# 读取图片 灰色会快
temp = cv2.imread(r'my_screenshot.png',cv2.IMREAD_GRAYSCALE)
theight, twidth = target.shape[:2]
tempheight, tempwidth = temp.shape[:2]
print("目标图宽高:"+str(twidth)+"-"+str(theight))
print("模板图宽高:"+str(tempwidth)+"-"+str(tempheight))
# 先缩放屏幕截图 INTER_LINEAR INTER_AREA
scaleTemp=cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
stempheight, stempwidth = scaleTemp.shape[:2]
print("缩放后模板图宽高:"+str(stempwidth)+"-"+str(stempheight))
# 匹配图片
res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if(max_val>=0.9):
# 计算出中心点
top_left = max_loc
bottom_right = (top_left[0] + twidth, top_left[1] + theight)
tagHalfW=int(twidth/2)
tagHalfH=int(theight/2)
tagCenterX=top_left[0]+tagHalfW
tagCenterY=top_left[1]+tagHalfH
#左键点击屏幕上的这个位置
pyautogui.click(tagCenterX,tagCenterY,button='left') # 点击
else:
print ("没找到")补充:python 根据图片特征识别点击
python 根据图片特征识别点击
import cv2
import numpy as np
import pyautogui
import time
class ImageClicker:
def __init__(self, target_image_path, retry_count=3, retry_interval=1, match_threshold=0.75):
self.target_image_path = target_image_path
self.retry_count = retry_count
self.retry_interval = retry_interval
self.match_threshold = match_threshold
# 加载目标图片
self.target_image = cv2.imread(self.target_image_path)
# 提取目标图片的 SIFT 特征
self.sift = cv2.SIFT_create()
self.kp1, self.des1 = self.sift.detectAndCompute(self.target_image, None)
def click_image(self):
for i in range(self.retry_count):
try:
# 获取浏览器窗口截图
screenshot = pyautogui.screenshot()
screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
# 提取截图的 SIFT 特征
kp2, des2 = self.sift.detectAndCompute(screenshot, None)
# 进行特征匹配
bf = cv2.BFMatcher()
matches = bf.knnMatch(self.des1, des2, k=2)
# 使用 Lowe's Ratio Test 筛选匹配结果
good = []
for m, n in matches:
if m.distance < self.match_threshold * n.distance: # 使用 match_threshold 阈值
good.append([m])
# 计算目标元素的位置
if len(good) > 0:
src_pts = np.float32([self.kp1[m[0].queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m[0].trainIdx].pt for m in good]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
h, w = self.target_image.shape[:2]
pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, M)
# 计算点击坐标
x = int((dst[0][0][0] + dst[2][0][0]) / 2) # 计算水平方向的中间位置
y = int((dst[0][0][1] + dst[2][0][1]) / 2) # 计算垂直方向的中间位置
# 点击目标元素
pyautogui.click(x, y)
return True # 点击成功
except Exception as e:
print(f"点击失败:{e}")
time.sleep(self.retry_interval)
return False # 点击失败
# 使用示例
image_clicker = ImageClicker('4.png', retry_count=5,
retry_interval=2,
match_threshold=0.8) # 设置 match_threshold 为 0.8
if image_clicker.click_image():
print("点击成功!")
else:
print("点击失败!")代码结构:
1.导入库:
cv2(OpenCV):用于图像处理、特征提取和匹配的库。numpy:用于处理图像数据所需的数值运算。pyautogui:用于控制鼠标和键盘,模拟点击操作。time:用于控制代码执行的暂停时间。
2.ImageClicker 类:
__init__(self, target_image_path, retry_count=3, retry_interval=1, match_threshold=0.75):
初始化类,设置一些参数:
target_image_path:目标图像的路径。retry_count:如果点击失败,重试的次数。retry_interval:两次重试之间的间隔时间(秒)。match_threshold:匹配阈值,用于判断目标图像与屏幕截图的匹配程度。值越高,匹配要求越严格。
加载目标图像 self.target_image。
创建 SIFT (尺度不变特征变换) 对象 self.sift,用于提取图像特征。
计算目标图像的 SIFT 特征 self.kp1, self.des1。
2.click_image(self):
1.循环尝试 retry_count 次:
- 获取屏幕截图
screenshot。将截图转换为 OpenCV 格式。提取截图的 SIFT 特征kp2, des2。 - 使用
cv2.BFMatcher进行特征匹配,得到匹配结果matches。使用 Lowe's Ratio Test 筛选匹配结果,得到good匹配列表。 - 如果找到匹配结果:
- 计算目标元素的位置(点击坐标)。
- 使用
pyautogui.click()模拟点击操作。 - 返回
True,表示点击成功。
如果没有找到匹配结果,则等待 retry_interval 秒后继续尝试。
如果所有尝试都失败,则返回 False,表示点击失败。
使用方法:
- 创建
ImageClicker对象,传入目标图像路径和其他参数。 - 调用
click_image()方法尝试点击目标图像。
代码示例:
image_clicker = ImageClicker('4.png', retry_count=5, retry_interval=2, match_threshold=0.8)
if image_clicker.click_image():
print("点击成功!")
else:
print("点击失败!")代码主要流程:
- 加载目标图像并提取其 SIFT 特征。
- 获取屏幕截图并提取其 SIFT 特征。
- 将目标图像的特征与截图的特征进行匹配。
- 使用 Lowe's Ratio Test 筛选匹配结果。
- 计算目标元素的位置(点击坐标)。
- 模拟点击目标元素。
注意:
- 为了使代码正常运行,需要安装必要的库:
opencv-python,pyautogui。 - 确保目标图像
4.png存在于代码所在的目录中。 - 调整
match_threshold值可以改变匹配的严格程度。 - 为了避免误点击,可以根据实际情况调整
retry_count和retry_interval。
参考资料:
python OpenCV 库中的 cv2.Canny() 函数来对图像进行边缘检测,并显示检测到的边缘特征
到此这篇关于python识别图标并点击的文章就介绍到这了,更多相关python识别图标内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
