剛開始學 OpenCV,用 cvSetCaptureProperty 指定從第幾幀開始讀取時就撞上一個怪問題。
我把 cvSetCaptureProperty 的 pos 設為 20,想取出第二十幀,結果拿到的卻不是第二十幀,而是亂數——有時是 23,有時是 18,具體數字還會隨不同影片而異。
測試環境是 Windows XP + OpenCV 2.1 + VS2008,程式中 pos 代表我設定的幀數,pos1 代表設定並取幀之後系統回報的當前幀數。理應兩者同步遞增,實際卻是 pos 正常遞增、pos1 亂跳。把同一份程式放到 Windows XP + OpenCV 1.0 + VC6.0 執行,結果完全正確,pos 與 pos1 都乖乖遞增。換了幾台電腦測試,結論一致。
於是問題變成:這是 OpenCV 2.1 的 bug,還是 VS2008 的問題?我查了好幾天資料,看到 SourceForge 上有人回報過 2.1 版 cvSetCaptureProperty 的 bug,描述與我遇到的幾乎相同,但沒有人給出解答。
#include "highgui.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cvNamedWindow("Example2", CV_WINDOW_AUTOSIZE);
CvCapture* capture = cvCreateFileCapture("d://11.avi");
IplImage* frame;
int pos = 0;
int pos1 = 0;
while (1)
{
cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, pos);
cout << pos;
frame = cvQueryFrame(capture);
pos1 = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES);
cout << "\t" << pos1 << endl;
if (!frame) break;
cvShowImage("Example2", frame);
char c = cvWaitKey(33);
if (c == 27) break;
pos++;
}
cvReleaseCapture(&capture);
cvDestroyWindow("Example2");
}
OpenCV 2.0 之後改用 FFmpeg 采集影片,1.0 用的是 VFW,差異就出在這裡。定位時 OpenCV 呼叫 FFmpeg 的 av_seek_frame():
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags);
flags 的可用值為:
AVSEEK_FLAG_BACKWARD = 1; ///< seek backward
AVSEEK_FLAG_BYTE = 2; ///< seeking based on position in bytes
AVSEEK_FLAG_ANY = 4; ///< seek to any frame, even non key-frames
FFmpeg 預設只選取關鍵幀,而 OpenCV 內部把 flag 固定寫成 0:
int ret = av_seek_frame(ic, video_stream, timestamp, 0);
因此 seek 的落點永遠是關鍵幀,pos1 自然就亂了。解法是把 0 改為 AVSEEK_FLAG_ANY:
int ret = av_seek_frame(ic, video_stream, timestamp, AVSEEK_FLAG_ANY);
重新編譯 OpenCV 函式庫之後即可正常取幀。理解這一點之後再回頭看,就能明白為什麼 1.0 不會出問題——VFW 的取幀模型本來就是逐幀索引,沒有關鍵幀這種跳躍機制。