I used mss module (https://pypi.org/project/mss/) to make screenshots. When calling function second time, I get black or white image. The weirdest thing is that ocasionally it succeeds.
I tried giving some time like sleep(1)
between calls but it didn't help.
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()
First image is always fine. Second image crushes most of the time, sometimes (especially when window is big) it surprisingly works well. I have no idea what might be the reason. I'll be greatful for any advice.
EDIT: I exchange mss screenshot function to pyautogui and it's still the same. It looks like the problem is somewhere else. This is new function:
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: Coordinates for the second image are fine. Even such a code gives a mistake when calling function second time (also checked by printing coordinates before taking screenshot):
img_1 = f.capture_left_figure('window_name1')
img_1.show()
img_1 = f.capture_left_figure('window_name1')
img_1.show()