2013-04-28 96 views
0

我有這個計劃,應該RGB視頻轉換爲灰度:轉換RGB視頻灰度OpenCV中

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); 

這是情況並非如此。任何人都可以幫助我修改它以正確地工作嗎?謝謝你:)

+0

[http://stackoverflow.com/questions/9289705/convert-video-from-colour-to-grayscale](http://stackoverflow.com/questions/9289705/convert-video-from-顏色到灰度) – 2013-04-28 18:21:55

+0

@AlexSmith我試過這個代碼,但它不起作用。輸出視頻只是旋轉和奇怪:) – user2329672 2013-04-28 18:28:26

回答

1

我認爲你將需要選擇你的編解碼器fourcc,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; 
} 
+0

tnx @ praks411爲您的代碼:)但我做錯了什麼。嘗試了一切,但仍然無法正常工作。 :S – user2329672 2013-04-29 19:31:20

+0

你面臨什麼問題?如果圖像旋轉,嘗試使用cvFlip api。在每個幀寫入waitKey(200)之後還要添加一些延遲。 – praks411 2013-04-29 21:27:18