import cv2 import numpy as np import pyautogui import time import keyboard # pip install…
- User
import cv2 import numpy as np import pyautogui import time import keyboard # pip install keyboard
设置是否要运行自动化操作的标志
automation_enabled = False
初始化一个计数器
print_count = 0 def perform_automation(): global print_count # 使用 global 声明以便在函数内修改全局变量 # 获取屏幕截图 screenshot = pyautogui.screenshot() screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
code# 读取需要识别的图像(确保此图像在屏幕上存在) template = cv2.imread('your_target_image.png', cv2.IMREAD_COLOR) # 匹配模板图像 result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) # 设置阈值来确定匹配的准确度 threshold = 0.8 if max_val >= threshold: # 获取匹配图像的中心点 template_width, template_height = template.shape[1], template.shape[0] center_x = max_loc[0] + int(template_width/2) center_y = max_loc[1] + int(template_height/2) # 将鼠标移动到图像中心点 pyautogui.moveTo(center_x, center_y) # 执行单击 pyautogui.rightClick() # 坐标位置 print_count += 1 print('Clicked at position:', center_x, center_y,('-'), print_count) time.sleep(0.6)按下特定键启用/禁用自动化
def toggle_automation(): global automation_enabled automation_enabled = not automation_enabled if automation_enabled: print("Automation enabled") else: print("Automation disabled")
设置热键,例如 F1,用于切换自动化操作开关
keyboard.add_hotkey('ctrl+alt+x', toggle_automation)
try: print("Service started. Press Ctrl+Alt+X to toggle automation on/off.") while True: # 检查自动化是否启用 if automation_enabled: perform_automation() except KeyboardInterrupt: # 处理中断信号,优雅地结束循环 print("Service stopped.") 运行代码时候CPU占用率偏高 禁用自动化下占用率更高
- Assistant
当你遇到高CPU使用率的问题,特别是在运行这类自动化脚本时,需要考虑的一个重点是循环运行的效率和等待时间。此脚本会不断检查是否启用自动化并执行
perform_automation函数,如果没有设置适当的等待时间,它将尽可能快地循环,这可能是导致高CPU使用率的原因之一。要解决这个问题,你可以在循环中加入短暂的休眠时间,以降低CPU的负荷。即使是很小的延迟,比如0.1秒,也能大大降低CPU的使用率。以下是一个调整过的脚本示例:
python