python获取所有可用摄像头(id + 名称)可用于opencv

 

缘起

python下使用opencv库使用VideoCapture调用摄像头时,只能传入枚举号,而不知道相应的相机名称。电脑有多个摄像头时,选择摄像头就会很不方便;电脑只有一个摄像头 时有时摄像头的ID也不一定是0。我们希望能够获取所有CV可以使用的摄像头信号源。

这个库的目的就是为解决这个问题而生。当前python3.6, 3.7, 3.8, 3.9, 3.10的64位win版本可以直接pip安装。

pip install pycameralist

有需要源码的也可以从我的gitee项目拉取。沃富仁波切/PyCameraListProject

测试代码1

#!/usr/bin/env python
# coding=utf-8

from PyCameraList.camera_device import test_list_cameras, list_video_devices, list_audio_devices

cameras = list_video_devices()
print(dict(cameras))
#return: {0: 'Intel(R) RealSense(TM) 3D Camera (Front F200) RGB', 1: 'NewTek NDI Video', 2: 'Intel(R) RealSense(TM) 3D Camera Virtual Driver', 3: 'Intel(R) RealSense(TM) 3D Camera (Front F200) Depth', 4: 'OBS-Camera', 5: 'OBS-Camera2', 6: 'OBS-Camera3', 7: 'OBS-Camera4', 8: 'OBS Virtual Camera'}
 
audios = list_audio_devices()
print(dict(audios))
#return:  {0: '麦克风阵列 (Creative VF0800)', 1: 'OBS-Audio', 2: '线路 (NewTek NDI Audio)'}

测试代码2

#!/usr/bin/env python
# coding=utf-8

from PyCameraList.camera_device import test_list_cameras, list_video_devices, list_audio_devices
import cv2 as cv


def show_in_cv(camera_id):
    cap = cv.VideoCapture(camera_id, cv.CAP_DSHOW)
    cap.set(cv.CAP_PROP_FRAME_WIDTH, 960)
    cap.set(cv.CAP_PROP_FRAME_HEIGHT, 540)
    cap.set(cv.CAP_PROP_FPS, 30)
    i = 0
    while True:
        suc, frame = cap.read()
        if not suc:
            break
        cv.imshow("preview camera", frame)
        cv.waitKey(30)
        i += 1
    return


def main():
    cameras = list_video_devices()
    print(f'\n\n===========================\ncamera_list: {cameras}')
    idx = 1
    camera_id = cameras[idx][0]
    camera_name = cameras[idx][1]
    print(f'\n\n===========================\npreview camera: camera_id={camera_id} camera_name={camera_name}')
    show_in_cv(camera_id)


if __name__ == '__main__':
    main()

 效果:

python获取所有可用摄像头(id + 名称)可用于opencv_第1张图片

你可能感兴趣的:(Python,opencv,python,计算机视觉)