Stack Exchange
grabscreen.py Python win32api
Any Linux or Mac OS equivalent libraries to Win32gui, or to this code ?
working on an outside project and this windows code will help me grab the screen. Havent been able to find any libraries that are similar. Thank you
def grab_screen(region=None):

hwin = win32gui.GetDesktopWindow()

if region:
        left,top,x2,y2 = region
        width = x2 - left + 1
        height = y2 - top + 1
else:
    width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)

signedIntsArray = bmp.GetBitmapBits(True)
img = np.fromstring(signedIntsArray, dtype='uint8')
img.shape = (height,width,4)

srcdc.DeleteDC()
memdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)
win32gui.DeleteObject(bmp.GetHandle())

return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)


pip install Pillow, obviously!

You can grab the screen with pyautogui:
import pyautogui
image = pyautogui.screenshot('filename.png')


You can do this :)
I think Mac OS can't use those WiIn32gui libraries.
instead you can use pillow for grabbing screen.
Screen size can be changed depends on the size you want.
import cv2
import numpy as np
import pyautogui
from PIL import ImageGrab

screen_w = 1920
screen_h = 1080

while True:
    rgb = ImageGrab.grab(bbox=(0, 0, screen_w, screen_h)) 
    rgb = np.array(rgb)

    cv2.imshow('window_frame', rgb)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break



Please, don't post code without an explanation as an answer. Try to explain what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

I added comments!
