VideoCapture returns empty frame in c++ but not in Python
After successfully compiling the following code with g++ -std=c++17 -o loadcams loadcams.cpp -lopencv_videoio -lopencv_core -lopencv_highgui
:
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
string loadcam(int sensor, int width, int height, int fps) {
return "nvcamerasrc sensor-id="+std::to_string(sensor)+" ! video/x-raw(memory:NVMM), width=(int)"+std::to_string(width)+", height=(int)"+std::to_string(height)+", format=(string)I420, framerate=(fraction)"+std::to_string(fps)+"/1 ! nvvidconv flip-method=6 ! video/x-raw, format=(string)I420 ! videoconvert ! video/x-raw, format=(string)BGR ! appsink";
}
int main() {
int WIDTH = 1920;
int HEIGHT = 1080;
int FPS = 60;
string loadcam1 = loadcam(1,WIDTH,HEIGHT,FPS);
Mat frame;
VideoCapture cap;
cap.open(loadcam1,CAP_GSTREAMER);
if (!cap.isOpened()) {
cerr << "Couldn't load cam 1\n";
return -1;
}
for(;;) {
cap >> frame;
if (frame.empty()) {
cerr << "ERROR! blank frame grabbed\n";
break;
}
imshow("Cam 1", frame);
if (waitKey(5) == 'q')
break;
}
return 0;
}
I get an error: window.cpp:331: error: (-215) size.width>0 && size.height>0 in function imshow
after executing.
However, I can display the live video with python using:
import cv2
import numpy as np
source = ("nvcamerasrc sensor-id=1 ! video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080, format=(string)I420, framerate=(fraction)60/1 ! nvvidconv flip-method=6 ! video/x-raw, format=(string)I420 ! videoconvert ! video/x-raw, format=(string)BGR ! appsink")
stream=cv2.VideoCapture(source, cv2.CAP_GSTREAMER)
grabbed,frame=stream.read()
while True:
grabbed,frame = stream.read()
cv2.imshow('Frame',frame)
if cv2.waitKey(1) == 27:
break
Is there a difference between how c++ needs to load gstreamer vs. python? Thanks for any help.