Search code examples
pythonimageopencvwebcam

Direct way to get camera screenshot


I'm working with Python OpenCV to a project that as an initial step involves capturing an image from a webcam; I tried to automate this process by using capture = cv2.VideoCapture and capture.read(), but the camera's video mode activation and its subsequent self-adjusting are too slow for what I want to achieve in the end.

Is there a more direct method of automatically capturing a screenshot with Python (and OpenCV)? If not, do you have any alternative suggestion? Thanks


Solution

  • If you want your camera screenshot function to be responsive, you need to initialize the camera capture outside of this function.

    On the following code snippet, the screenshot function is triggered by pressing c:

    import cv2
    
    def screenshot():
        global cam
        cv2.imshow("screenshot", cam.read()[1]) # shows the screenshot directly
        #cv2.imwrite('screenshot.png',cam.read()[1]) # or saves it to disk
    
    if __name__ == '__main__':
    
        cam = cv2.VideoCapture(0) # initializes video capture
    
        while True:
            ret, img = cam.read()
            cv2.imshow("cameraFeed", img) # a window is needed as a context for key capturing (here, I display the camera feed, but there could be anything in the window)
            ch = cv2.waitKey(5)
            if ch == 27:
                break
            if ch == ord('c'): # calls screenshot function when 'c' is pressed
                screenshot()
    
        cv2.destroyAllWindows()
    

    To clarify: cameraFeed window is only here for the purpose of the demo (where screenshot is triggered manually). If screenshot is called automatically in your program, then you don't need this part.

    Hope it helps!