如何修复代码中的颜色检测?

问题描述 投票:0回答:1

导入pyautogui 进口键盘 导入时间

跑步=真

print("脚本将在 5 秒后开始。") time.sleep(5) # 等待5秒再开始

跑步时: Keyboard.press_and_release('x') # 每次颜色检测前按 'x'

# Capture the screen and get the color at the specified position
screenshot = pyautogui.screenshot()
target_color = (255, 0, 0)  # Replace with the RGB values of your target color
target_position = (100, 100)  # Replace with the coordinates of the position to monitor

# The pixel_color format is (red, green, blue, alpha)
pixel_color = screenshot.getpixel(target_position)

# Check if the pixel color matches the target color
if pixel_color == target_color:
    time.sleep(1)  # Adjust this delay as needed to avoid rapid repeated key presses

if keyboard.is_pressed('F10'):
    running = False
    print("Script stopped by user.")

我希望它按 x,然后等到检测到颜色,然后按 x 并重复这 2 个操作,但它要么是垃圾邮件 x,要么只按 x 一次,就这样。

有人可以帮助我吗?

我尝试尽我所能并进行研究,但我仍然很新,我不知道如何

python pyautogui image-recognition
1个回答
0
投票

pyautogui
所需的包是
pyscreeze
pyscreeze
可以为您获取像素的颜色。

pyscreeze.pixelMatchesColor(x: {__len__}, y: Any, expectedRGBColor: {__len__}, tolerance: int = 0) -> bool

如果 x, y 处的像素与预期的颜色匹配,则返回 True RGB 元组,每种颜色表示从 0 到 255,在可选的范围内 宽容。

有了这个,你不需要 5 秒的延迟来获取坐标处的像素。

from time import sleep
from typing import Optional

import pynput.keyboard as kb
from pyscreeze import pixelMatchesColor, RGB

TERMINATE: bool = False
KEYBOARD: Optional[kb.Listener] = None

"""RGB is a collections.namedtuple. You can use regular tuple (255, 0, 0)"""
PIXEL: RGB = RGB(255, 0, 0)

kb.Key.x = 88

PRESSED = set()
HOTKEYS = [
    {kb.Key.x},
    {kb.Key.f10},
]


def on_key_pressed(key: int | kb.Key | kb.KeyCode):
    if isinstance(key, kb.KeyCode):
        key = key.vk

    if key not in PRESSED:
        PRESSED.add(key)

        """I set this up this way incase you want to add control keys to the hotkey.
        Example: {kb.Key.ctrl_l, kb.Key.x}"""
        for hotkeys in HOTKEYS:
            if all(hotkey in PRESSED for hotkey in hotkeys):
                for hotkey in hotkeys:
                    if hotkey == key:
                        if hotkeys == HOTKEYS[0]:  # hotkey x for getting the color at pixel(x = 100, y = 100)
                            if pixelMatchesColor(x = 100, y = 100, expectedRGBColor = PIXEL):
                                pass
                        elif hotkeys == HOTKEYS[1]:  # hotkey f10 for terminating the script.
                            global TERMINATE
                            TERMINATE = True


def on_key_released(key: int | kb.Key | kb.KeyCode):
    if isinstance(key, kb.KeyCode):
        key = key.vk

    if key in PRESSED:
        PRESSED.remove(key)


KEYBOARD: kb.Listener = kb.Listener(on_press = on_key_pressed, on_release = on_key_released)
KEYBOARD.start()

while not TERMINATE:
    sleep(1 / 1000)

KEYBOARD.stop()



如果您决定更改获取像素的热键,则可以使用它来获取

pynput.keyboard.Key
中不是常量的关键代码。

import pynput
from time import sleep
from typing import Any


def on_key_press(key: Any):
    if 'KeyCode' in str(type(key)):
        key = key.vk

    print(key)


keyboard = pynput.keyboard.Listener(on_press = on_key_press)
keyboard.start()

while True:
    sleep(1 / 1000)
© www.soinside.com 2019 - 2024. All rights reserved.