由于项目需要,近期一直在做基于摄像机方面的研究,前几天写了一个小程序,要实时显示摄像机捕捉到的图像,本来以为是一件很简单的事情,却让我费了不少功夫,也学到了不少东西。摄像机都有自己的SDK,截取部分有自己的API,我所要做的就是把摄像机截取到的图像格式(yuv422)转换到我显示所需要的rgb格式(这个我近期会抽时间研究下,然后写点东西),然后通过调用OpenCV函数来显示就可以了,但我遇到的问题却是一个又一个。 在创建完OpenCV所支持的图像数据结构IplImage后,需要把转换后的rgb格式复制到IplImage数据结构中,在复制的过程中,我把行列顺序弄反,结果后来得到的图像是花屏。另外一个比较有意思的事情是关于OpenCV函数cvShowImage()和cvWaitKey(),之前都是用这两个函数显示一幅图像,从来没有做过连续显示(视频显示)的工作,当我确认我的IplImage是千真万确正确后,我用cvShowImage()函数显示却得到了一幅灰色图像,而且鼠标显示一直处于忙碌状态,因为我要用while(1)循环一直调用cvShowImage()函数,我当时把cvWaitKey()函数放在了while循环外面,抱着试试看的态度我把cvWaitKey()函数放在循环内部cvShowImage()的后面,图像就可以正常显示了,google下,原来有人遇到和我一样的问题:http://www.opencv.org.cn/forum/viewtopic.php?f=1&t=3324&p=11520,看了上面的解释,自己还是有些不明白,主要是对Windows编程了解很少,里面关于消息处理机制的东西不太明白。 为了方便读者看,把Windows平台下的cvWaitKey()代码贴在这里:
CV_IMPL int cvWaitKey( int delay ){ int time0 = GetTickCount(); for (;;) { CvWindow * window; MSG message; int is_processed = 0 ; if ( (delay > 0 && abs(( int )(GetTickCount() - time0)) >= delay) || hg_windows == 0 ) return - 1 ; if ( delay <= 0 ) GetMessage( & message, 0 , 0 , 0 ); else if ( PeekMessage( & message, 0 , 0 , 0 , PM_REMOVE) == FALSE ) { Sleep( 1 ); continue ; } for ( window = hg_windows; window != 0 && is_processed == 0 ; window = window -> next ) { if ( window -> hwnd == message.hwnd || window -> frame == message.hwnd ) { is_processed = 1 ; switch (message.message) { case WM_DESTROY: case WM_CHAR: DispatchMessage( & message); return ( int )message.wParam; case WM_KEYDOWN: TranslateMessage( & message); default : DispatchMessage( & message); is_processed = 1 ; break ; } } } if ( ! is_processed ) { TranslateMessage( & message); DispatchMessage( & message); } }}关于cvWaitKey()函数的说明:
函数原型:int cvWaitKey( int delay=0 );The cvWaitKey() function asks the program to stop and wait for a keystroke. If a positive argument is given, the program will wait for that number of milliseconds and then continue even if nothing is pressed.If the argument is set to 0 or to a negative number, the program will wait indefinitely for a keypress.鉴于以上几点:我现在的处理方法是:把cvWaitKey()函数放在循环内部cvShowImage()的后面,参数选1,1ms的时间还是可以忽略不计的。这样就可以实时的显示摄像机图像了。