-
-
Save ZacharyZhang-NY/8413d467212844e3dabf81fc4ee3c500 to your computer and use it in GitHub Desktop.
Take screenshot of specific window on MacOS with python
This file contains 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.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment