当前位置: 首页 > news >正文

python pyautogui实现图片识别点击失败后重试

安装库 

pip install Pillow
pip install opencv-python

confidence作用

confidence 参数是用于指定图像匹配的信度(或置信度)的,它表示图像匹配的准确程度。这个参数的值在 0 到 1 之间,数值越高表示匹配的要求越严格。
具体来说,confidence 参数用于调整在屏幕上搜索目标图像时的匹配精度:
0.0 表示完全不匹配。
1.0 表示完全匹配。
在实际应用中,图像匹配的信度可以帮助你处理一些图像上的细微差异。例如,屏幕上的图像可能因为分辨率、光线、颜色等原因与原始图像有些不同。通过调整 confidence 参数,你可以设置一个合理的阈值,使得图像匹配过程既不太严格(导致找不到图像),也不太宽松(导致误匹配)。
举个例子,如果你设置 confidence=0.8,那么只有当屏幕上的图像与目标图像的相似度达到 80% 以上时,才会被认为是匹配的。

识别图片点击

import pyautogui
import time
import osdef locate_and_click_image(image_path, retry_interval=2, max_retries=5, click_count=1, confidence=None):"""定位图片并点击指定次数。:param image_path: 图片路径:param retry_interval: 重试间隔时间(秒):param max_retries: 最大重试次数:param click_count: 点击次数:param confidence: 图像匹配的信度(0到1之间),需要安装 OpenCV:return: 图片的位置 (x, y, width, height) 或 None(如果未找到)"""if not os.path.isfile(image_path):print(f"错误:图片路径无效或文件不存在: {image_path}")return Noneretries = 0while retries < max_retries:try:if confidence is not None:location = pyautogui.locateOnScreen(image_path, confidence=confidence)else:location = pyautogui.locateOnScreen(image_path)if location is not None:print(f"找到图片: {image_path},位置: {location}")center = pyautogui.center(location)for _ in range(click_count):pyautogui.click(center)print(f"点击图片中心位置。点击次数:{_ + 1}")return locationelse:print(f"未找到图片: {image_path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")time.sleep(retry_interval)retries += 1except pyautogui.ImageNotFoundException:print(f"未找到图片: {image_path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")time.sleep(retry_interval)retries += 1print(f"达到最大重试次数: {max_retries},未找到图片: {image_path}")return Nonedef main():image_path = '1.png'  # 替换为你的图片路径retry_interval = 2max_retries = 5click_count = 1confidence = 0.8  # 如果不使用 OpenCV,请将此参数设置为 Nonelocation = locate_and_click_image(image_path, retry_interval, max_retries, click_count, confidence)if location:print("操作完成。")else:print("未能定位到图片,程序结束。")if __name__ == "__main__":locate_and_click_image('1.png', retry_interval=2, max_retries=5, click_count=2, confidence=0.8)

优化代码,识别多张图片并点击

import pyautogui
import time
import osdef locate_and_click_image(path, retry_interval=2, max_retries=5, click_count=1, confidence=None):if not os.path.isfile(path):print(f"错误:图片路径无效或文件不存在: {path}")return Noneretries = 0while retries < max_retries:try:if confidence is not None:location = pyautogui.locateOnScreen(path, confidence=confidence)else:location = pyautogui.locateOnScreen(path)if location is not None:print(f"找到图片: {path},位置: {location}")center = pyautogui.center(location)for _ in range(click_count):pyautogui.click(center)print(f"点击图片中心位置。点击次数:{_ + 1}")return locationelse:print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")time.sleep(retry_interval)retries += 1except pyautogui.ImageNotFoundException:print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")time.sleep(retry_interval)retries += 1print(f"达到最大重试次数: {max_retries},未找到图片: {path}")return Nonedef main():images = [{'path': '1.png', 'retry_interval': 2, 'max_retries': 5, 'click_count': 1, 'confidence': 0.8},{'path': '3.png', 'retry_interval': 2, 'max_retries': 5, 'click_count': 1, 'confidence': 0.8},# 添加更多图片]for image in images:location = locate_and_click_image(**image)if location:print(f"图片 {image['path']} 操作完成。")else:print(f"未能定位到图片 {image['path']},程序结束。")if __name__ == "__main__":main()

优化代码,识别多张图片,只要识别到图片就结束循环

import pyautogui
import time
import osdef locate_and_click_image(path, retry_interval=2, max_retries=5, click_count=1, confidence=None):if not os.path.isfile(path):print(f"错误:图片路径无效或文件不存在: {path}")return Noneretries = 0while retries < max_retries:try:if confidence is not None:location = pyautogui.locateOnScreen(path, confidence=confidence)else:location = pyautogui.locateOnScreen(path)if location is not None:print(f"找到图片: {path},位置: {location}")center = pyautogui.center(location)for _ in range(click_count):pyautogui.click(center)print(f"点击图片中心位置。点击次数:{_ + 1}")return Trueelse:print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")time.sleep(retry_interval)retries += 1except pyautogui.ImageNotFoundException:print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")time.sleep(retry_interval)retries += 1print(f"达到最大重试次数: {max_retries},未找到图片: {path}")return Falsedef main():images = [{'path': '1.png', 'retry_interval': 2, 'max_retries': 5, 'click_count': 1, 'confidence': 0.8},{'path': '3.png', 'retry_interval': 2, 'max_retries': 5, 'click_count': 1, 'confidence': 0.8},{'path': '4.png', 'retry_interval': 2, 'max_retries': 5, 'click_count': 1, 'confidence': 0.8},# 添加更多图片]for image in images:success = locate_and_click_image(**image)if success:print(f"图片 {image['path']} 操作完成。")breakelse:print(f"未能定位到图片 {image['path']}。")if __name__ == "__main__":main()

如有帮助,请多多支持作者! 你鼓励是我最大的动力~QAQ~

相关文章:

  • 【linux】操作系统使用wget下载网络文件,内核tcpv4部分运行日志
  • 【ClickHouse】副本、分片集群 (六)
  • 随机产生一些江河上的坐标数据
  • 秋招突击——6/17——复习{整理昨天的面试资料}——新作{删除链表倒数第n个节点}
  • Jmeter多个请求按照比例并发压测的几种方式
  • POI:接收上传上来的excel,解析并导入到数据库
  • Kafka中的时间轮算法
  • 2024广东省职业技能大赛云计算赛项实战——Ansible部署Zabbix
  • error: the type ‘const zjloc::<lambda(const Vec2i, const Vec2i)>’
  • JAVA NIO(二) Buffer和Channel
  • Elasticsearch:倒数排序融合 - Reciprocal rank fusion - 8.14
  • go的有栈和无栈
  • C#开发-集合使用和技巧(一)常用集合和方法介绍
  • 设计模式——访问者模式
  • python从入门到精通1:注释
  • 【译】React性能工程(下) -- 深入研究React性能调试
  • bootstrap创建登录注册页面
  • es6--symbol
  • IDEA常用插件整理
  • JavaScript-Array类型
  • jdbc就是这么简单
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • PV统计优化设计
  • python docx文档转html页面
  • Tornado学习笔记(1)
  • vue数据传递--我有特殊的实现技巧
  • Vue组件定义
  • 第十八天-企业应用架构模式-基本模式
  • 个人博客开发系列:评论功能之GitHub账号OAuth授权
  • 警报:线上事故之CountDownLatch的威力
  • 每个JavaScript开发人员应阅读的书【1】 - JavaScript: The Good Parts
  • 如何设计一个微型分布式架构?
  • 腾讯优测优分享 | Android碎片化问题小结——关于闪光灯的那些事儿
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • kubernetes资源对象--ingress
  • Spring第一个helloWorld
  • 阿里云重庆大学大数据训练营落地分享
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • ​油烟净化器电源安全,保障健康餐饮生活
  • #LLM入门|Prompt#1.7_文本拓展_Expanding
  • #传输# #传输数据判断#
  • (06)Hive——正则表达式
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (floyd+补集) poj 3275
  • (笔试题)合法字符串
  • (二十四)Flask之flask-session组件
  • (附源码)ssm捐赠救助系统 毕业设计 060945
  • (三) prometheus + grafana + alertmanager 配置Redis监控
  • (十二)Flink Table API
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • .bat批处理(六):替换字符串中匹配的子串
  • .bat批处理(十):从路径字符串中截取盘符、文件名、后缀名等信息
  • .NET core 自定义过滤器 Filter 实现webapi RestFul 统一接口数据返回格式
  • .net 程序发生了一个不可捕获的异常
  • .NET编程——利用C#调用海康机器人工业相机SDK实现回调取图与软触发取图【含免费源码】