본문 바로가기

# Python/# pyautogui

[보기쉬운 pyautogui] 3. 이미지 - locateOnScreen, screenshot, pixel

728x90
반응형

 

import pyautogui

<RGB>

pyautogui.pixel(x, y) : (x, y)의 RGB값을 반환

pyautogui.pixelMatchesColor(x, y, (R, G, B)) : (x, y)의 RGB값이 (R, G, B) 숫자 값과 같은지 판단.

RGB = pyautogui.pixel(x, y)
pyautogui.pixelMatchesColor(x2, y2, RGB)
pyautogui.pixelMatchesColor(x3, y3, (34, 167, 242))

<이미지>

pyautogui.screentshot( ) : 현재 화면을 스크린샷

 

img = pyautogui.screenshot()
img.save('screenshot.png')

 

현재 화면을 스크린샷 찍고, 해당 파일을 'screenshot.png'로 저장

 

 

pyautogui.locateOnScreen('button.png') : 해당 이미지가 있는지 확인, 없으면 None 반환

 

btn = pyautogui.locateOnScreen('button.png')
if btn :
	pyautogui.click(btn)

 

'button.png'와 같은 이미지를 해당 화면에 찾아서 해당 버튼이 존재하면 클릭

<속도 개선>

1. 흑백으로 이미지 검색

img = pyautogui.locateOnScreen('img.png', grayscale = True)

 

2. 이미지의 범위를 정함

img = pyautogui.locateOnScreen('img.png', region=(left, top, width, height))

 

3. 이미지의 정확도를 낮춤

pip install opencv-pyton를 먼저 설치해야함

img = pyautogui.locateOnScreen('img.png', confidence = 0.5)

 

confidence의 default 값은 0.999이다.

 

 

<예시 코드 - 시간 종료>

import time
import pyautogui

def find_in_time(img_file, timeout=10):
    start = time.time()
    img = None
    while img is None:
        img = pyautogui.locateOnScreen('img.png')
        end = time.time()
        if end - start > timeout: break
    return img


def img_click(img_file, timeout=10):
    img = find_in_time(img_file, timeout)
    if img:
        pyautogui.click(img)
    else:
        print("time out")


img_click('img.png', 10)
728x90
반응형