我想要阅读并使用openCV显示的视频 engine2.avi 。这是我的代码:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
int main(int argc, char** argv)
{
string filename = "D:\\BMDvideos\\engine2.avi";
VideoCapture capture(filename);
Mat frame;
if( !capture.isOpened() )
throw "Error when reading steam_avi";
namedWindow("w", 1);
for( ; ; )
{
capture >> frame;
//if(!frame)
// break;
imshow("w", frame);
waitKey(20); // waits to display frame
}
waitKey(0);
}
如果我的文件具有编解码器YUV 4:2:2 (UYVY)
(我使用Direct-Show录制视频),此代码不起作用,但是当我使用视频时,我可以使用openCV !!
有人知道这如何运作?
更新
在阅读了一些链接后,建议捕获异常将解决问题,我修改了我的代码。它没有帮助,但这里是修改后的代码:
cv::VideoCapture cap("d:\\BMDvideos\\engine2.avi");
cv::Mat frame;
try
{
cap >> frame;
}
catch(cv::Exception ex)
{
std::cout << ex.what() << std::endl;
}
catch(...)
{
std::cout << "Unknown exception" << std::endl;
}
程序在cap>>frame
崩溃。我引用了类似的问题,但他们在YUV(4:2:0)中使用了一个帧,而我的视频是UYVY(4:2:2)。如何将其转换为RGB颜色模型?
更新2:
在karlphillip的建议之后,我使用了OpenCV2.4.3,但是我仍然使用下面的代码得到了同样的错误:
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\opencv.hpp>
using namespace cv;
using namespace std;
int main(){
cv::Mat frame;
cv::VideoCapture cap("d:\\BMDvideos\\B\\Aufnahme.avi");
if(!cap.isOpened())
{
cout << "Error can't find the file"<<endl;
}
while(1){
if(!cap.read(frame))
imshow("",frame);
cv::waitKey(33);
}
return 0;
}
答案 0 :(得分:9)
以下是一些可能对您有所帮助的链接:
修改强>:
我必须先澄清一些事情: OpenCV能够从视频文件中读取YUV帧,因为它是完成这项工作的底层库(FFmpeg / GStreamer)。 OpenCV还支持在特定类型的YUV and RGB到cvCvtColor()
与CV_YCrCb2RGB
或CV_RGBYCrCb
之间进行转换。
再次检查您的问题后,我注意到您没有指定发生的错误类型。您可以通过在屏幕上打印消息而不是throw
来从捕获界面do a better job dealing possible failure {{3}}。
我测试了您分享的视频文件,使用以下代码在窗口上播放时没有任何问题:
#include <cv.h>
#include <highgui.h>
#include <iostream>
int main(int argc, char* argv[])
{
cv::VideoCapture cap(argv[1]);
if (!cap.isOpened())
{
std::cout << "!!! Failed to open file: " << argv[1] << std::endl;
return -1;
}
cv::Mat frame;
for(;;)
{
if (!cap.read(frame))
break;
cv::imshow("window", frame);
char key = cvWaitKey(10);
if (key == 27) // ESC
break;
}
return 0;
}
如果由于某种原因,捕获界面无法打开文件,它将立即退出应用程序,而不是仅仅在cap.read(frame)
崩溃。
答案 1 :(得分:0)
如果你只是想要显示视频,这里的代码对我有用, 请检查它是否对您有所帮助。
#include <stdio.h>
#include <opencv2/opencv.hpp>
int main(){
CvCapture *camera=cvCaptureFromFile("C:\\test.avi");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
/*if(img){
cvSaveImage("C:/opencv.jpg",img);
}*/
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
希望这会对你有所帮助。
答案 2 :(得分:-1)
我意识到,VideoCapture对象需要opencv_ffmpeg310_64.dll。 将此dll复制到二进制文件夹后,您的VideoCapture对象应该能够读取视频文件。