Skip to content

Instantly share code, notes, and snippets.

@dougbacelar
Created September 25, 2021 15:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dougbacelar/2116a834f5e4e1cd069659463a07dde5 to your computer and use it in GitHub Desktop.
Save dougbacelar/2116a834f5e4e1cd069659463a07dde5 to your computer and use it in GitHub Desktop.
Take screenshot of specific window on MacOS with python
from Quartz import CGWindowListCopyWindowInfo, kCGNullWindowID, kCGWindowListOptionAll
import cv2 as cv
import numpy
from time import time
from PIL import Image
import os
windowId = None
windowName = 'Desktop'
def findWindowId():
global windowId
print('searching window id')
windowList = CGWindowListCopyWindowInfo(
kCGWindowListOptionAll, kCGNullWindowID)
for window in windowList:
print(window.get('kCGWindowName', ''))
if(windowName.lower() in window.get('kCGWindowName', '').lower()):
windowId = window['kCGWindowNumber']
print('found window id %s' % windowId)
return True
print('unable to find window id')
return False
def takeScreenshot():
if windowId is None:
if findWindowId() is False:
return
imageFileName = 'test-img.png'
# -x mutes sound and -l specifies windowId
os.system('screencapture -x -l %s %s' % (windowId, imageFileName))
img = Image.open(imageFileName)
print(img)
img = numpy.array(img)
os.remove(imageFileName)
return img
loopTime = time()
while(True):
screenshot = takeScreenshot()
if screenshot is not None:
cv.imshow('cv', screenshot)
# measure frames per second
print('FPS {}'.format(1 / (time() - loopTime)))
loopTime = time()
if cv.waitKey(1) == ord('q'): # quit script when pressing 'q' key
cv.destroyAllWindows()
break
print('Done.')
@rajkundu
Copy link

This helped me tremendously - thank you so much!

@xunzhaoLoVe
Copy link

fp = builtins.open(filename, "rb")

FileNotFoundError: [Errno 2] No such file or directory: 'test-img.png' - - why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment