VideoCapture fails to open onboard camera L4T 21.5 OpenCV 2.4.9

I want to build a project to realize a video capture ,process by my code ,h264 encode and rtsp.but i happened to a problem
#include <stdio.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

int main(int argc, char** argv) {

// first part of sender pipeline
cv::VideoCapture cap("v4l2src ! video/x-raw, framerate=30/1, width=640, height=480, format=RGB ! videoconvert ! appsink");
if (!cap.isOpened()) {
    printf("=ERR= can't create video capture\n");
    return -1;

// second part of sender pipeline
cv::VideoWriter writer;"appsrc ! videoconvert ! x264enc noise-reduction=10000 tune=zerolatency byte-stream=true threads=4 ! mpegtsmux ! udpsink host=localhost port=9999"
            , 0, (double)30, cv::Size(640, 480), true);
if (!writer.isOpened()) {
    printf("=ERR= can't create video writer\n");
    return -1;

cv::Mat frame;
int key;

while (true) {

    cap >> frame;
    if (frame.empty())

    /* Process the frame here */

    writer << frame;
    key = cv::waitKey( 30 );

i can’t open the v4l2src

anyone help me ?Thanks.

Have you enabled gstreamer support when building opencv ?
You may check this thread

Furthermore, this should not be your case, but I remember some people faced problems with pipelines in VideoWriter, where just adding a space at the end of the string was a workaround. But I think this was related to IP address in pipeline having dots, and it was then processed as a file name with extension.

hi Honey_Patouceul
Thank you for your guidance!The code is just for testing.When I test it, I met a problem as you said:
OpenCV Error: Unsupported format or combination of formats (Gstreamer Opencv backend doesn’t support this codec acutally.) in CvVideoWriter_GStreamer::open, file /home/ubuntu/opencv-2.4.9/modules/highgui/src/cap_gstreamer.cpp, line 505
terminate called after throwing an instance of ‘cv::Exception’
what(): /home/ubuntu/opencv-2.4.9/modules/highgui/src/cap_gstreamer.cpp:505: error: (-210) Gstreamer Opencv backend doesn’t support this codec acutally. in function CvVideoWriter_GStreamer::open


Do you know how to solve it?
Thank you in advance.

The problem seems in writer.
I would advise to build and install your own opencv-3.2.0 lib enabling gstreamer-1.0 support and use it instead of 2.4.9.
If you have a lot of sources tied to opencv2 API, you can rather try building 2.4.13 enabling gstreamer-1.0 support.