Screen Capture with OpenCV and Python-2.7

后端 未结 3 1712
迷失自我
迷失自我 2020-11-30 03:46

I\'m using Python 2.7 and OpenCV 2.4.9.

I need to capture the current frame that is being shown to the user and load it as an cv::Mat

3条回答
  •  野性不改
    2020-11-30 04:13

    This is the updated answer for the answer by @Neabfi

    import time
    
    import cv2
    import numpy as np
    from mss import mss
    
    mon = {'top': 160, 'left': 160, 'width': 200, 'height': 200}
    with mss() as sct:
        # mon = sct.monitors[0]
        while True:
            last_time = time.time()
            img = sct.grab(mon)
            print('fps: {0}'.format(1 / (time.time()-last_time)))
            cv2.imw('test', np.array(img))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
    

    And to save to a mp4 video

    import time
    
    import cv2
    import numpy as np
    from mss import mss
    
    
    def record(name):
        with mss() as sct:
            # mon = {'top': 160, 'left': 160, 'width': 200, 'height': 200}
            mon = sct.monitors[0]
            name = name + '.mp4'
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            desired_fps = 30.0
            out = cv2.VideoWriter(name, fourcc, desired_fps,
                                  (mon['width'], mon['height']))
            last_time = 0
            while True:
                img = sct.grab(mon)
                # cv2.imshow('test', np.array(img))
                if time.time() - last_time > 1./desired_fps:
                    last_time = time.time()
                    destRGB = cv2.cvtColor(np.array(img), cv2.COLOR_BGRA2BGR)
                    out.write(destRGB)
                if cv2.waitKey(25) & 0xFF == ord('q'):
                    cv2.destroyAllWindows()
                    break
    
    
    record("Video")
    
    

提交回复
热议问题