Skip to content

Instantly share code, notes, and snippets.

@dougbacelar
Created September 25, 2021 15:47
Show Gist options
  • Select an option

  • Save dougbacelar/2116a834f5e4e1cd069659463a07dde5 to your computer and use it in GitHub Desktop.

Select an option

Save dougbacelar/2116a834f5e4e1cd069659463a07dde5 to your computer and use it in GitHub Desktop.

Revisions

  1. Doug Bacelar created this gist Sep 25, 2021.
    63 changes: 63 additions & 0 deletions take-screenshot-mac.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    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.')