3

我使用 mss 模块 ( https://pypi.org/project/mss/ ) 来制作屏幕截图。第二次调用函数时,我得到黑白图像。最奇怪的是,它偶尔会成功。

我尝试sleep(1)在通话之间留出一些时间,但没有帮助。

import mss
import mss.tools
from PIL import Image
import win32gui

def screen_part(top, left, width, height):
    '''
    Returns a PIL image of the part of the screen
    '''
    with mss.mss() as sct:
        # The screen part to capture
        monitor = {"top": top, "left": left, "width": width, "height": height}
        output = "sct-{top}x{left}_{width}x{height}.png".format(**monitor)

        # Grab the data
        sct_img = sct.grab(monitor)

        # Convert to PIL Image
        img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")

        return img

def window_coordinates(win_name):
    '''
    Returns rect for the window --> tuple

    '''
    x = y = w = h = None
    def callback(hwnd, extra):
        if win32gui.GetWindowText(hwnd) == win_name:
            nonlocal x, y, w, h
            rect = win32gui.GetWindowRect(hwnd)
            x_ = rect[0]
            y_ = rect[1]
            w_ = rect[2] - x
            h_ = rect[3] - y

    win32gui.EnumWindows(callback, None)
    return x, y, w, h

def capture_left_figure(win_name):
    '''
    x_karty / (x_table + w_table) * (x_t + w_t)

    '''

   x, y, w, h = window_coordinates(win_name)

    left = round(439 / 1084 * w) + x
    top = round(1743 / 1963  * h) + y
    w = round(50 / 1084 * w)
    h = round(39 / 1963 * h)

    print(left, top, w, h)

    img = screen_part(top, left, w, h)
    return img

img_1 = f.capture_left_figure('window_name1')
img_1.show()

img_2 = f.capture_left_figure('window_name2')
img_2.show()

第一张图总是好的。第二张图片在大多数情况下都会崩溃,有时(尤其是当窗口很大时)它出奇地好用。我不知道可能是什么原因。我会很感激任何建议。

编辑:我将 mss 屏幕截图功能交换为 pyautogui,它仍然是一样的。看起来问题出在其他地方。这是新功能:

def screen_part_2(top, left, width, height):
    '''
    Returns a PIL image of the part of the screen
    '''
    img = pyautogui.screenshot(region=(left, top, width, height))

    return img

EDIT2:第二张图片的坐标很好。即使这样的代码在第二次调用函数时也会出错(在截屏前也通过打印坐标进行检查):

img_1 = f.capture_left_figure('window_name1')
img_1.show()

img_1 = f.capture_left_figure('window_name1')
img_1.show()
4

0 回答 0