在OpenCV中将rgb视频转换为灰度

时间:2013-04-28 18:06:50

标签: opencv video rgb grayscale

我有这个程序应该将rgb视频转换为灰度:

CvCapture* capture = 0;
capture = cvCreateFileCapture( "sample.avi" );
if(!capture)
{
    return -1;
}
IplImage *bgr_frame=cvQueryFrame(capture);//Init the video read
double fps = cvGetCaptureProperty (capture,CV_CAP_PROP_FPS);

CvSize size = cvSize((int)cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH),(int)cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT));
CvVideoWriter *writer = cvCreateVideoWriter("izlaz.avi",CV_FOURCC_DEFAULT,fps,size);

IplImage *grayScaleImage = cvCreateImage(size ,IPL_DEPTH_8U,1);



while( (bgr_frame=cvQueryFrame(capture)) != NULL )
{

    cvCvtColor(bgr_frame, grayScaleImage, CV_BGR2GRAY);
    cvWriteFrame( writer, grayScaleImage );


}

cvReleaseVideoWriter( &writer );
cvReleaseCapture( &capture );

情况并非如此。谁能帮我修改它才能正常工作?谢谢:)

1 个答案:

答案 0 :(得分:1)

我认为你需要在你的编解码器中选择四个,CV_FOURCC_DEFAULT对我来说不起作用。我尝试了CV_FOURCC('P','I','M,'1')和CV_FOURCC('M','J','P','G')。他们都为我工作。

以下是我尝试的示例代码。

#include<opencv2\opencv.hpp>
#include<iostream>
using namespace cv;

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

    char *my_file = "C:\\vid_an2\\Wildlife.wmv";

    std::cout<<"Video File "<<my_file<<std::endl;

    cv::VideoCapture input_video;

    if(input_video.open(my_file))
    {
       std::cout<<"Video file open "<<std::endl;
    }
    else
    {
        std::cout<<"Not able to Video file open "<<std::endl;
    }
    int fps = input_video.get(CV_CAP_PROP_FPS);
    int frameCount = input_video.get(CV_CAP_PROP_FRAME_COUNT);
    double fheight = input_video.get(CV_CAP_PROP_FRAME_HEIGHT);
    double fwidth = input_video.get(CV_CAP_PROP_FRAME_WIDTH);
    CvSize fsize;
    fsize.width = fwidth;
    fsize.height = fheight;

    CvVideoWriter *new_writer = cvCreateVideoWriter("brg_file.avi",CV_FOURCC('M','J','P','G'), fps,fsize, 0); 
    std::cout<<"Video Frame Rate "<<fps<<std::endl;
    std::cout<<"Video Frame Count "<<frameCount<<std::endl;
    Mat cap_img;
    Mat gry_img;
    IplImage new_img;
    while(input_video.grab())
   {
        if(input_video.retrieve(cap_img))
        {
                cvtColor(cap_img, gry_img, CV_RGB2GRAY);
                new_img = gry_img.operator IplImage();  
                int ret = cvWriteFrame(new_writer, (const IplImage*)&new_img);
                std::cout<<"Wrote Frame "<<ret<<std::endl;

        }
    }
    cvReleaseVideoWriter(&new_writer);

    return 0;
}