欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Python实现图片定位与自动输入文字

Python实现图片定位与自动输入文字

2025/2/24 7:17:04 来源:https://blog.csdn.net/exlink2012/article/details/143908239  浏览:    关键词:Python实现图片定位与自动输入文字

简介

本文介绍如何使用Python实现在屏幕上定位特定图片,并在目标位置自动输入文字的功能。主要使用OpenCV进行图像识别,PyAutoGUI实现鼠标控制和键盘输入。

主要功能

  1. 在屏幕上查找指定图片位置
  2. 自动移动鼠标到目标位置
  3. 模拟鼠标点击
  4. 自动输入中文文字

技术要点

1. 图片定位

使用OpenCV的模板匹配功能,通过cv2.matchTemplate()函数在屏幕截图中查找目标图片。匹配度阈值设为0.7,可根据实际需求调整。

2. 屏幕操作

  • 使用ImageGrab获取屏幕截图
  • 使用pyautogui控制鼠标移动和点击
  • 设置FAILSAFE = True启用PyAutoGUI的安全机制

3. 中文输入

通过剪贴板实现中文输入:

  1. 将文字复制到剪贴板
  2. 使用Ctrl+V模拟粘贴操作

使用说明

环境准备

pip install opencv-python
pip install pyautogui
pip install pillow
pip install numpy
pip install pyperclip

使用步骤

  1. 准备要查找的目标图片(test.png)
  2. 运行程序
  3. 程序会自动查找图片位置并执行点击和输入操作

注意事项

  1. 确保目标图片清晰可见
  2. 图片匹配阈值可根据需要调整
  3. 建议在执行自动操作前关闭输入法

完整代码

import cv2
import numpy as np
import pyautogui
import time
from PIL import ImageGrab
import pyperclipdef type_chinese_text(text):"""使用剪贴板输入中文"""pyperclip.copy(text)  # 复制到剪贴板pyautogui.hotkey('ctrl', 'v')  # 粘贴def find_image_on_screen(template_path, threshold=0.7):"""在屏幕上查找指定图片的位置"""try:# 读取模板图片template = cv2.imread(template_path)template_height, template_width = template.shape[:2]# 截取整个屏幕screen = np.array(ImageGrab.grab())screen = cv2.cvtColor(screen, cv2.COLOR_RGB2BGR)# 模板匹配result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)locations = np.where(result >= threshold)matches = []for pt in zip(*locations[::-1]):matches.append({'left': pt[0],'top': pt[1],'width': template_width,'height': template_height,'confidence': result[pt[1], pt[0]]})matches.sort(key=lambda x: x['confidence'], reverse=True)return matchesexcept Exception as e:print(f"查找图片时发生错误: {e}")return []def interact_with_image(matches, text_to_type="你好"):"""移动到图片位置并输入文字"""if not matches:print("未找到目标图片")return False# 使用最佳匹配best_match = matches[0]# 计算图片中心位置center_x = best_match['left'] + best_match['width'] // 2center_y = best_match['top'] + best_match['height'] // 2try:# 移动鼠标print(f"正在移动鼠标到位置: ({center_x}, {center_y})")pyautogui.moveTo(center_x, center_y, duration=0.5)# 点击位置print("点击位置")pyautogui.click()# 等待一小段时间确保点击生效time.sleep(0.5)# 输入中文print(f"正在输入文字: {text_to_type}")type_chinese_text(text_to_type)print("操作完成")return Trueexcept Exception as e:print(f"操作失败: {e}")return Falsedef main():# 设置PyAutoGUI的安全设置pyautogui.FAILSAFE = True# 设置中文输入pyautogui.PAUSE = 0.5  # 增加操作间隔时间print("开始查找图片...")# 查找图片matches = find_image_on_screen('test.png')if matches:print(f"找到 {len(matches)} 个匹配位置")for i, match in enumerate(matches, 1):print(f"\n匹配 {i}:")print(f"位置: 左={match['left']}, 上={match['top']}")print(f"大小: {match['width']}x{match['height']}")print(f"匹配度: {match['confidence']:.2%}")# 移动鼠标并输入文字interact_with_image(matches)else:print("未找到目标图片")if __name__ == '__main__':try:main()except KeyboardInterrupt:print("\n程序已停止")except Exception as e:print(f"发生错误: {e}")

总结

本文介绍的方法可以实现屏幕图片定位和自动输入文字的功能,适用于自动化测试、重复性操作等场景。通过调整参数和添加更多功能,可以满足不同的自动化需求。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词