How to correctly check if a camera is available?

后端 未结 4 394
情歌与酒
情歌与酒 2021-01-12 06:46

I am using OpenCV to open and read from several webcams. It all works fine, but I cannot seem to find a way to know if a camera is available.

I tried this code (cam

4条回答
  •  日久生厌
    2021-01-12 07:17

    You can try this code:

    from __future__ import print_function
    import numpy as np
    import cv2
    
    # detect all connected webcams
    valid_cams = []
    for i in range(8):
        cap = cv2.VideoCapture(i)
        if cap is None or not cap.isOpened():
            print('Warning: unable to open video source: ', i)
        else:
            valid_cams.append(i)
    
    caps = []
    for webcam in valid_cams:
        caps.append(cv2.VideoCapture(webcam))
    
    while True:
        # Capture frame-by-frame
        for webcam in valid_cams:
            ret, frame = caps[webcam].read()
            # Display the resulting frame
            cv2.imshow('webcam'+str(webcam), frame)
        k = cv2.waitKey(1)
        if k == ord('q') or k == 27:
            break
    
    # When everything done, release the capture
    for cap in caps:
        cap.release()
    
    cv2.destroyAllWindows()
    

提交回复
热议问题