图像获取与录制

说明

  1. 使用前,请关闭ROS程序,摄像头只能同时被一个程序访问。

  2. 参考下面的示例代码,更改 gstreamer_pipeline() 函数的默认参数,从而更改摄像头的配置参数。

示例代码

import cv2

def gstreamer_pipeline(
    sensor_id=1,         # 摄像头编号
    capture_width=1280,  # 采集分辨率width
    capture_height=720,  # 采集分辨率height
    display_width=1280,
    display_height=720,
    framerate=60,        # 采集帧率
    flip_method=2,       # 视频翻转模式,因为模块的摄像头是反装的,所以使用2(180翻转)
):
    return (
        "nvarguscamerasrc sensor-id=%d ! "
        "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"
        % (
            sensor_id,
            capture_width,
            capture_height,
            framerate,
            flip_method,
            display_width,
            display_height,
        )
    )

def show_camera():
    print(gstreamer_pipeline(flip_method=2))
    cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=2), cv2.CAP_GSTREAMER)
    if cap.isOpened():
        window_handle = cv2.namedWindow("CSI Camera", cv2.WINDOW_AUTOSIZE)
        # Window
        while cv2.getWindowProperty("CSI Camera", 0) >= 0:
            ret_val, img = cap.read()
            cv2.imshow("CSI Camera", img)
            # This also acts as
            keyCode = cv2.waitKey(30) & 0xFF
            # Stop the program on the ESC key
            if keyCode == 27:
                break
        cap.release()
        cv2.destroyAllWindows()
    else:
        print("Unable to open camera")


if __name__ == "__main__":
    show_camera()