从视频错误中提取帧

时间:2014-03-13 04:57:56

标签: python opencv python-2.7 video

我正在尝试从avi视频中提取所有帧并显示它们。代码如下:

import cv2
from cv2 import cv
import time
cap=cv2.VideoCapture('video1.avi')
count=cap.get(cv.CV_CAP_PROP_FRAME_COUNT)
cap.set(cv.CV_CAP_PROP_POS_FRAMES, count-1)
cv2.namedWindow("Display", cv2.CV_WINDOW_AUTOSIZE)

while True:
    ret,frame=cap.read()
    cv2.imshow("Display", frame)
    time.sleep(0.1)

我得到的错误是:

cv2.imshow("Display", frame)
cv2.error: ..\..\..\src\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0

代码有问题吗?如果没有,那么如何删除错误?

2 个答案:

答案 0 :(得分:2)

如果在imshow之前frame为null,你必须打破循环,并使用waitKey代替sleep。

所以将代码更改为

while True:
    ret,frame=cap.read()
    if not ret: break
    cv2.imshow("Display", frame)
    cv2.waitKey(20)

答案 1 :(得分:0)

尝试使用此代码从视频中提取帧。

它对我有用

#include <stdio.h>
    #include <iostream>
    #include <conio.h>
    #include <opencv2/core/core.hpp>
    #include <opencv2/highgui/highgui.hpp>
    #include <opencv2/imgproc/imgproc.hpp>

    using namespace cv;

    int main(int argc, char** argv)
    {
        // Read a video file from file

        CvCapture* capture = cvCaptureFromAVI("C:\\Users\\Pavilion\\Documents\\Visual Studio 2013\\Projects\\video\\optical illusions.avi");
        int loop = 0;
        IplImage* frame = NULL;
        Mat matframe;
        Mat img_hsv, img_rgb;
        char fname[20];
        do
        {
            // capture frames from video

            frame = cvQueryFrame(capture);
            matframe = cv::cvarrToMat(frame);

            // create a window to show frames
            cvNamedWindow("video_frame", CV_WINDOW_AUTOSIZE);

            // Display images in a window
            cvShowImage("video_frame", frame);
            sprintf(fname, "C:\\Users\\Pavilion\\Documents\\Visual Studio 2013\\Projects\\video\\video\\frames\\frame%d.jpg", loop);

            // write images to a folder
            imwrite(fname, matframe);
            // Convert RGB to HSV

            cvtColor(img_rgb, img_hsv, CV_RGB2HSV);

            loop++;
            cvWaitKey(10);
        } while (frame != NULL);
        return 0;
    }