目录

1.测试摄像头是否可用

查看是否连接到摄像头

 CSI摄像头测试

USB摄像头测试

2.若以上步骤正常,进行oepncv读取摄像头数据

(1)CSI摄像头

1.安装v4l2-utils协助工具

2.查看摄像头详细参数--支持的图片大小和对应帧率

3.安装管道gstreamer库

4.使用opencv读取图片例程

(2)USB摄像头


1.测试摄像头是否可用

查看是否连接到摄像头

ls /dev/video*

 CSI摄像头测试

nvgstcapture-1.0

USB摄像头测试

#首先安装camorama库
sudo apt-get install camorama
#然后运行
camorama /dev/video0 #这里我只安装了USB摄像头

2.若以上步骤正常,进行oepncv读取摄像头数据

(1)CSI摄像头

1.安装v4l2-utils协助工具

sudo apt install v4l-utils 

2.查看摄像头详细参数--支持的图片大小和对应帧率

v4l2-ctl --device=/dev/video0 --list-formats-ext

3.安装管道gstreamer库

sudo add-apt-repository universe
sudo add-apt-repository multiverse
sudo apt-get update
sudo apt-get install gstreamer1.0-tools gstreamer1.0-alsa gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav
sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libgstreamer-plugins-good1.0-dev libgstreamer-plugins-bad1.0-dev

4.使用opencv读取图片例程

#coding=utf-8
import cv2

# 设置gstreamer管道参数
def gstreamer_pipeline(
    capture_width=1280, #摄像头预捕获的图像宽度
    capture_height=720, #摄像头预捕获的图像高度
    display_width=1280, #窗口显示的图像宽度
    display_height=720, #窗口显示的图像高度
    framerate=60,       #捕获帧率
    flip_method=0,      #是否旋转图像
):
    return (
        "nvarguscamerasrc ! "
        "video/x-raw(memory:NVMM), "
        "width=(int)%d, height=(int)%d, "
        "format=(string)NV12, framerate=(fraction)%d/1 ! "
        "nvvidconv flip-method=%d ! "
        "video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
        "videoconvert ! "
        "video/x-raw, format=(string)BGR ! appsink"
        % (
            capture_width,
            capture_height,
            framerate,
            flip_method,
            display_width,
            display_height,
        )
    )

if __name__ == "__main__":
    #根据摄像头参数设置
    capture_width = 1280   #
    capture_height = 720
    framerate = 60			# 帧数
    #展示图片大小
    display_width = 1280
    display_height = 720
    flip_method = 0			# 方向

    # 创建管道
    #管道与视频流绑定
    cap = cv2.VideoCapture(gstreamer_pipeline(capture_width,capture_height,display_width,display_height,framerate,flip_method), cv2.CAP_GSTREAMER)

    if cap.isOpened():
        window_handle = cv2.namedWindow("CSI Camera", cv2.WINDOW_AUTOSIZE)

        # 逐帧显示
        while cv2.getWindowProperty("CSI Camera", 0) >= 0:
            ret_val, img = cap.read()
            cv2.imshow("CSI img", img)

            keyCode = cv2.waitKey(30) & 0xFF
            if keyCode == 27:# ESC键退出
                break

        cap.release()
        cv2.destroyAllWindows()
    else:
        print("open error")

(2)USB摄像头

import cv2

cap = cv2.VideoCapture('./dev/video0') #用ls /dev/video* 可读取出来

while(1):
    ret,frame = cap.read()  
    if ret:
        cv2.imshow("USB_img",frame) 
        keyCode = cv2.waitKey(30) & 0xFF
        if keyCode == 27:# ESC键退出
            break 
    
cap.release()
cv2.destroyAllWindows()

更多推荐