我可以使用OpenCV的VideoReader class通过IP摄像机流或任何视频文件的路径对其进行解码。此解码过程正在按预期使用GPU,到目前为止没有问题。这是简单的代码,可以很好地运行并使用GPU进行解码:
int main()
{
const std::string fname("rtsp://user:pwd@192.168.1.108");
// const std::string fname("/path/to/video/file.mp4"); // this also works
cv::cuda::GpuMat d_frame;
cv::Ptr<cv::cudacodec::VideoReader> d_reader = cv::cudacodec::createVideoReader(fname);
Mat frame;
for (;;)
{
if (!d_reader->nextFrame(d_frame))
break;
Mat myMat(d_frame);
cv::imshow("GPU", myMat);
if (cv::waitKey(3) > 0)
break;
}
return 0;
}
我想使用GPU像VideoCapture(0)
一样从我的摄像头捕获流。我知道@berak提到here:无法用VideoCapture
1-是否可以通过将GPU与VideoReader类一起使用来进行流传输?因为VideoReader类仅接受字符串,而不接受索引。
2-使用GPU进行流传输还有哪些其他方式?
答案 0 :(得分:0)
1) 是的,似乎是这样!我在 openCV GPU 示例 here 中找到了以下代码。你可以试一试。不过,您需要使用 OpenGL 构建 OpenCV……目前这就是我遇到的问题。
2) 我不确定其他选项,但这里是 Github 上的代码。
#include <iostream>
#include "opencv2/opencv_modules.hpp"
#if defined(HAVE_OPENCV_CUDACODEC)
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <opencv2/core.hpp>
#include <opencv2/core/opengl.hpp>
#include <opencv2/cudacodec.hpp>
#include <opencv2/highgui.hpp>
int main(int argc, const char* argv[])
{
std::cout << "Starting,...\n";
const std::string fname = "0";
cv::namedWindow("CPU", cv::WINDOW_NORMAL);
cv::namedWindow("GPU", cv::WINDOW_OPENGL);
cv::cuda::setGlDevice();
cv::Mat frame;
cv::VideoCapture reader(fname);
cv::cuda::GpuMat d_frame;
cv::Ptr<cv::cudacodec::VideoReader> d_reader = cv::cudacodec::createVideoReader(fname);
cv::TickMeter tm;
std::vector<double> cpu_times;
std::vector<double> gpu_times;
int gpu_frame_count=0, cpu_frame_count=0;
for (;;)
{
tm.reset(); tm.start();
if (!reader.read(frame))
break;
tm.stop();
cpu_times.push_back(tm.getTimeMilli());
cpu_frame_count++;
cv::imshow("CPU", frame);
if (cv::waitKey(3) > 0)
break;
}
for (;;)
{
tm.reset(); tm.start();
if (!d_reader->nextFrame(d_frame))
break;
tm.stop();
gpu_times.push_back(tm.getTimeMilli());
gpu_frame_count++;
cv::imshow("GPU", d_frame);
if (cv::waitKey(3) > 0)
break;
}
if (!cpu_times.empty() && !gpu_times.empty())
{
std::cout << std::endl << "Results:" << std::endl;
std::sort(cpu_times.begin(), cpu_times.end());
std::sort(gpu_times.begin(), gpu_times.end());
double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) / cpu_times.size();
double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) / gpu_times.size();
std::cout << "CPU : Avg : " << cpu_avg << " ms FPS : " << 1000.0 / cpu_avg << " Frames " << cpu_frame_count << std::endl;
std::cout << "GPU : Avg : " << gpu_avg << " ms FPS : " << 1000.0 / gpu_avg << " Frames " << gpu_frame_count << std::endl;
}
return 0;
}
#else
int main()
{
std::cout << "OpenCV was built without CUDA Video decoding support\n" << std::endl;
return 0;
}
#endif