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

 更新时间:2024年06月26日 15:23:02   作者:U盘失踪了  
这篇文章主要介绍了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 os
def 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 None
    retries = 0
    while 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 location
            else:
                print(f"未找到图片: {image_path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
                time.sleep(retry_interval)
                retries += 1
        except pyautogui.ImageNotFoundException:
            print(f"未找到图片: {image_path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
            time.sleep(retry_interval)
            retries += 1
    print(f"达到最大重试次数: {max_retries},未找到图片: {image_path}")
    return None
def main():
    image_path = '1.png'  # 替换为你的图片路径
    retry_interval = 2
    max_retries = 5
    click_count = 1
    confidence = 0.8  # 如果不使用 OpenCV,请将此参数设置为 None
    location = 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 os
def 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 None
    retries = 0
    while 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 location
            else:
                print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
                time.sleep(retry_interval)
                retries += 1
        except pyautogui.ImageNotFoundException:
            print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
            time.sleep(retry_interval)
            retries += 1
    print(f"达到最大重试次数: {max_retries},未找到图片: {path}")
    return None
def 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 os
def 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 None
    retries = 0
    while 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 True
            else:
                print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
                time.sleep(retry_interval)
                retries += 1
        except pyautogui.ImageNotFoundException:
            print(f"未找到图片: {path},{retry_interval}秒后重试...(重试次数: {retries + 1}/{max_retries})")
            time.sleep(retry_interval)
            retries += 1
    print(f"达到最大重试次数: {max_retries},未找到图片: {path}")
    return False
def 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']} 操作完成。")
            break
        else:
            print(f"未能定位到图片 {image['path']}。")
if __name__ == "__main__":
    main()

到此这篇关于python pyautogui实现图片识别点击失败后重试的文章就介绍到这了,更多相关python pyautogui图片识别失败内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python检验用户输入密码的复杂度

    Python检验用户输入密码的复杂度

    这篇文章主要介绍了Python检验用户输入密码的复杂度,在用户设置密码的时候检测输入的密码大小写数字等,需要的朋友可以参考下
    2023-04-04
  • 简单谈谈python基本数据类型

    简单谈谈python基本数据类型

    在Python中,能够直接处理的数据类型有以下几种:#整型 int,#浮点型 float,#布尔型 bool,#复数型 (在python中用小写 j ,表示虚部,用其他的字母不行)complex
    2018-09-09
  • python中bytes和str类型的区别

    python中bytes和str类型的区别

    这篇文章主要介绍了python中bytes和str类型的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • python 找出list中最大或者最小几个数的索引方法

    python 找出list中最大或者最小几个数的索引方法

    今天小编就为大家分享一篇python 找出list中最大或者最小几个数的索引方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • python如何在字典中插入或增加一个字典

    python如何在字典中插入或增加一个字典

    这篇文章主要介绍了python如何在字典中插入或增加一个字典问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-03-03
  • python使用socket实现的传输demo示例【基于TCP协议】

    python使用socket实现的传输demo示例【基于TCP协议】

    这篇文章主要介绍了python使用socket实现的传输demo,结合实例形式分析了Python使用socket库基于TCP协议实现的客户端与服务器端相关操作技巧,需要的朋友可以参考下
    2019-09-09
  • Python网络爬虫之爬取微博热搜

    Python网络爬虫之爬取微博热搜

    这篇文章主要介绍了Python网络爬虫之爬取微博热搜的相关知识,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-04-04
  • python 字典的概念叙述和使用方法

    python 字典的概念叙述和使用方法

    Python中还有一个很重要的数据类型就是字典,其实集合的底层使用的也是字典,这篇文章主要介绍了python 字典的概念叙述和使用方法,需要的朋友可以参考下
    2023-02-02
  • 自定义PyCharm快捷键的设置方式

    自定义PyCharm快捷键的设置方式

    这篇文章主要介绍了自定义PyCharm快捷键的设置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • python如何运行js语句

    python如何运行js语句

    在本篇内容里小编给大家整理的是一篇关于python如何运行js语句的相关内容,有兴趣的朋友们可以参考下。
    2020-09-09

最新评论