我正在做一个视频监控项目
我看不到从RGB到灰色的转换;我得到一个灰色的黑色窗口
你能帮帮我解决这个问题吗? (附代码)
另外,如何获得当前帧和前一帧之间的差异?
非常感谢。
伊兰
#include "stdafx.h"
#include <stdio.h> // For printf
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
int main()
{
int key = 0;
CvCapture* capture = cvCaptureFromAVI( "macroblock.mpg" );
IplImage* frame = cvQueryFrame( capture );
IplImage* gray = cvCreateImage(cvGetSize(frame),IPL_DEPTH_8U,1);
cvCvtColor(frame, gray, CV_RGB2GRAY);
if ( !capture )
{
fprintf( stderr, "Cannot open AVI!\n" );
return 1;
}
int fps = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FPS );
cvNamedWindow( "video", CV_WINDOW_AUTOSIZE );
cvNamedWindow( "grayvideo", CV_WINDOW_AUTOSIZE );
while( key != 'x' )
{
frame = cvQueryFrame( capture );
if(key==27 )break;
cvShowImage( "video",frame );
cvShowImage( "grayvideo",gray );
key = cvWaitKey( 1000 / fps );
}
cvDestroyWindow( "video" );
cvReleaseCapture( &capture );
return 0;
}
答案 0 :(得分:3)
您需要将每个帧从颜色转换为灰度。如果您在开始时执行一次,它不会自动转换。所以你需要添加
cvCvtColor(frame, gray, CV_BGR2GRAY);
在致电cvQueryFrame
后,进入您的while循环。
答案 1 :(得分:1)
您的代码存在一些问题。
cvCaptureFromAVI()
; cvQueryFrame()
可能会失败,您还需要检查它的返回值; cvCvtColor(frame, gray, CV_RGB2GRAY);
,然后显示灰框; 看起来像这样的代码是不是更容易阅读/理解?
int main()
{
CvCapture* capture = cvCaptureFromAVI( "macroblock.mpg" );
if ( !capture )
{
fprintf( stderr, "Cannot open AVI!\n" );
return 1;
}
int fps = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FPS );
printf("FPS: %d\n", fps);
cvNamedWindow( "video", CV_WINDOW_AUTOSIZE );
cvNamedWindow( "grayvideo", CV_WINDOW_AUTOSIZE );
int key = 0;
IplImage* gray = NULL;
IplImage* prev_frame = NULL;
while( key != 'x' )
{
frame = cvQueryFrame( capture );
if (!frame)
{
// print error and abort the loop
break;
}
cvShowImage( "video", frame );
if (!gray) // allocate space for the GRAY frame only once
{
gray = cvCreateImage(cvGetSize(frame), frame->depth,1);
}
cvCvtColor(frame, gray, CV_RGB2GRAY); // convert RGB frame to GRAY
cvShowImage( "grayvideo", gray );
if (!prev_frame) // allocate space for the GRAY frame only once
{
prev_frame = cvCreateImage(cvGetSize(frame), frame->depth,1);
cvCopy( frame, prev_frame, 0 );
}
// perform process to compute the "difference" of the current
// and previous frames:
// <add your code here>
// then, update prev_frame now so in the next iteration it holds the previous frame
cvCopy( frame, prev_frame, 0 );
key = cvWaitKey( 1000 / fps );
if ( key==27 ) // ESC was pressed
break;
}
cvDestroyWindow( "video" );
cvDestroyWindow( "grayvideo" );
cvReleaseCapture( &capture );
if (gray)
cvReleaseImage( &gray );
if (prev_frame)
cvReleaseImage( &prev_frame );
return 0;
}
答案 2 :(得分:0)
根据您的需要使用以下opencv
功能之一:
subtract(img_current,img_prev, img_diff);
absdiff(img_current, img_prev, img_diff);