Python3 opencv 链接 usb 摄像头

最近碰到一个问题需要外接 USB 摄像头。简单研究了一下,还是浪费了一些时间的。现在把代码丢这里造福大众。

其中 camera_idx 就是 camera 的 id,内置的(系统默认的) 一般为0,外接的可以从1开始尝试。

如果有任何错误欢迎指出。

 

import cv2
import time

# single funct, return a numpy frame object
def snapShot(camera_idx = 1):# camera_idx default = 0 normally usb = 1 /or you can try with 1,2,3
    cap = cv2.VideoCapture(camera_idx)
    # get a frame
    ret, frame = cap.read()
    cap.release()
    return frame
    

# continuously write picture, refresh picture itself
def snapShotCt(camera_idx = 1):# camera_idx default = 0 normally usb = 1 /or you can try with 1,2,3
    cap = cv2.VideoCapture(camera_idx)
    # get a frame
    ret, frame = cap.read()

    while ret:
        cv2.imwrite("capture.jpg", frame) # write picture 
        time.sleep(1) # delay 1s, delete if possible
        ret, frame = cap.read() # next frame
        break # for test, delete in real use
    cap.release()

 

你可能感兴趣的:(工具)