Created
September 25, 2021 15:47
-
-
Save dougbacelar/2116a834f5e4e1cd069659463a07dde5 to your computer and use it in GitHub Desktop.
Take screenshot of specific window on MacOS with python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.') |
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'test-img.png' - - why?
Thank you so much ! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This helped me tremendously - thank you so much!