How do I access my webcam in Python?

前端 未结 4 1220
孤独总比滥情好
孤独总比滥情好 2020-12-02 06:09

I would like to access my webcam from Python.

I tried using the VideoCapture extension (tutorial), but that didn\'t work very well for me, I had to work around some

相关标签:
4条回答
  • 2020-12-02 06:27

    gstreamer can handle webcam input. If I remeber well, there are python bindings for it!

    0 讨论(0)
  • 2020-12-02 06:29

    OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work. As of 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python

    More information on using OpenCV with Python.

    An example copied from Displaying webcam feed using opencv and python:

    import cv2
    
    cv2.namedWindow("preview")
    vc = cv2.VideoCapture(0)
    
    if vc.isOpened(): # try to get the first frame
        rval, frame = vc.read()
    else:
        rval = False
    
    while rval:
        cv2.imshow("preview", frame)
        rval, frame = vc.read()
        key = cv2.waitKey(20)
        if key == 27: # exit on ESC
            break
    cv2.destroyWindow("preview")
    
    0 讨论(0)
  • 2020-12-02 06:32
    import cv2 as cv
    
    capture = cv.VideoCapture(0)
    
    while True:
        isTrue,frame = capture.read()
        cv.imshow('Video',frame)
        if cv.waitKey(20) & 0xFF==ord('d'):
            break
    
    capture.release()
    cv.destroyAllWindows()
    

    0 <-- refers to the camera , replace it with file path to read a video file

    cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed

    0 讨论(0)
  • 2020-12-02 06:39

    John Montgomery's, answer is great, but at least on Windows, it is missing the line

    vc.release()
    

    before

    cv2.destroyWindow("preview")
    

    Without it, the camera resource is locked, and can not be captured again before the python console is killed.

    0 讨论(0)
提交回复
热议问题