首页 > 编程语言 >python pyautogui实现图片识别点击失败后重试

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

时间:2024-06-22 22:29:15浏览次数:3  
标签:pyautogui retries confidence retry python image 重试 path click

安装库 

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()

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

标签:pyautogui,retries,confidence,retry,python,image,重试,path,click
From: https://blog.csdn.net/qq_26086231/article/details/139871032

相关文章

  • python入门基础知识(错误和异常)
    本文部分内容来自菜鸟教程Python基础教程|菜鸟教程(runoob.com) 本人负责概括总结代码实现。以此达到快速复习目的目录语法错误异常异常处理try/excepttry/except...elsetry-finally语句抛出异常用户自定义异常内置异常类型常见的标准异常类型语法错误P......
  • 【python】pandas:Series详解
    Series是Pandas库中的一个核心数据结构,用于处理一维数组型数据,并带有与之相关的数据标签(通常称为“索引”)。Series可以被视为一个固定大小的、有序的、可以包含任何数据类型的数组。以下是关于Series的详细介绍:定义Series是一个一维的、大小可变的、可以包含任何数据类型......
  • python读数据,并且 csv格式的,如何应对。
    s545112015022319.txt要求 通过python 导入程序  高度(距地) 时间 气温  气压 湿度  露点 温露差 虚温 风向 风速 纬度差 经度差0   0 0.0 0.9 1015 38-11.8 12.7 1.6 203 1 0.0 0.01   10 0.......
  • Python语法
    Python领导:不要分号1.基礎变量定义x=100判断if循环for...in...、whilebreak、continue函数def函数名(参数):函数体类class类名:def__init__(self,p1,p2):self.param1=p1self.param2=p2类变量、实例变量__repr__......
  • 使用 Python 进行测试(7)...until you make it
    总结我很懒,我想用最少的行动实现目标,例如生成测试数据。我们可以:使用随机种子保证数据的一致性。>>>random.seed(769876987698698)>>>[random.randint(0,10)for_inrange(10)][10,9,1,9,10,6,5,10,1,9]>>>random.seed(769876987698698)>>>[random.r......
  • 2024华为OD机试真题- 找出作弊的人-(C++/Python)-C卷D卷-100分
     2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++) 题目描述公司组织了一次考试,现在考试结果出来了,想看一下有没人存在作弊行为,但是员工太多了,需要先对员工进行一次过滤,再进一步确定是否存在作弊行为。过滤的规则为:找到分差最小的员工ID对(p1,p2)列表,要求p1<......
  • python-opencv批量处理图像文件(附代码)
        这里以cifar100数据集为例。cifar100数据集保存在train文件夹中,其中一共有100类图片,每类图片被保存在不同的子文件夹中,每类图片500张,其具体文件夹如下。    首先要引入cv2和os库,接着还要提前设置好图像保存路径和原图像文件路径。如果这里设置的不对的话......
  • python socket写客户端
    客户端开发流程1、创建客户端套接字对象2、和服务端套接字建立连接3、发送数据4、接收数据5、关闭客户端套接字注意:客户端是指运行在用户的设备上,服务端是指运行在服务器设备上的,专门为客户端提供数据服务socket类的使用1、导入socket模块importsocket2、使用s......
  • 538个代码示例!麻省理工教授的Python程序设计+人工智能案例实践
    Python简单易学,且提供了丰富的第三方库,可以用较少的代码完成较多的工作,使开发者能够专注于如何解决问题而只花较少的时间去考虑如何编程。此外,Python还具有免费开源、跨平台、面向对象、胶水语言等优点,在系统编程、图形界面开发、科学计算、Web开发、数据分析、人工智能等方面......
  • python学习笔记-10
    面向对象编程-下1.私有化属性语法:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。使用私有化属性的场景:1.把特定的一个属性隐藏起来,不让类的外部进行直接调用。2.不让属性的值随意改变。3.不让子类继承。classPerson():def__init__(self):......