Search code examples
pythonpython-3.xopencvwebcam

Capturing webcam snapshot with python silently


How is it possible to capture a snapshot of webcam or stream webcam in python without popping up windows?


Solution

  • Using opencv-python package, the following piece of code momentarily captures the webcam information and saves the image in the directory specified. Note: The webcam indicator does light up for a fraction of second. I am not sure how that can be avoided as of now.

    import cv2
    webcam = cv2.VideoCapture(1) # Number which capture webcam in my machine
    # try either VideoCapture(0) or (1) based on your camera availability
    # in my desktop it works with (1)
    check, frame = webcam.read()
    cv2.imwrite(filename=r'<Your Directory>\saved_img.jpg', img=frame)
    webcam.release()
    

    This piece of code can be written in a bat file and you can trigger this for what ever event you are looking for (like startup security)