实际上使用opencv打开摄像头的操作都是一样的,但是由于TX2的板载摄像头是MIPI的CSI-2接口,它和USB有些不一样,需要增加一些配置。
先附上个人的代码
/**
* 获取 TX2 板载摄像头的打开参数
* @param width 采集视频的宽度
* @param height 采集视频的高度
* @param fps 采集视频 fps
* @return 板载摄像头的打开参数字符串
*/
static std::string getTegraPipeline(int width, int height, int fps=60) {
return std::string("nvarguscamerasrc ! ") +
std::string("video/x-raw(memory:NVMM), ") +
std::string("width=(int)") + std::to_string(width) + ", " +
std::string("height=(int)") + std::to_string(height) + ", " +
std::string("format=(string)NV12, ") +
std::string("framerate=(fraction)") + std::to_string(fps) + "/1 ! " +
std::string("nvvidconv flip-method=2 ! ") +
std::string("video/x-raw, ") +
std::string("format=(string)BGRx ! ") +
std::string("videoconvert ! ") +
std::string("video/x-raw, ") +
std::string("format=(string)BGR ! ") +
std::string("appsink");
}
// 是否使用 tx2 板载摄像头, `true` 使用 tx2 板载摄像头, `false` 不使用板载摄像头
static bool use_tx2 = false;
/**
* 读取 `config.json` 配置文件,打开摄像头
* @return 返回 opencv 摄像头实例化
*/
static cv::VideoCapture getCap()
{
std::string camera = "tx2";
int width = 1280;
int height = 720;
int fps = 30;
if (camera == "tx2") {
// Define the gstream pipeline
std::string pipeline = getTegraPipeline(width, height, fps);
std::cout << "Using pipeline: \n\t" << pipeline << "\n";
use_tx2 = true;
// Create OpenCV capture object, ensure it works.
return cv::VideoCapture(pipeline, cv::CAP_GSTREAMER);
} else {
return cv::VideoCapture(camera);
}
}
int main(int argc, char** argv)
{
// 初始化摄像头
cv::VideoCapture cap = getCap();
if (!cap.isOpened()) {
std::cout << "Connection failed" << std::endl;
return -1;
}
// View video
cv::Mat frame;
while (1) {
cap >> frame;
if (frame.empty()) break;
//使用 tx2 时图像需要翻转
if (use_tx2 == true) {
cv::flip(frame, frame, -1);
}
imshow("capture", frame);
cv::waitKey(1);
}
return 0;
}
其实就是做个简单的封装,因为它的摄像头有许多参数可以设置,详细的参数介绍