视频帧提取错误

1 投票
2 回答
2707 浏览
提问于 2025-04-17 22:04

我正在尝试从一个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

试试这个代码,它可以从视频中提取帧。

对我来说是有效的。

#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;
    }
2

在调用 imshow 之前,如果 frame 是空的,就得跳出这个循环。同时,应该用 waitKey 来代替 sleep。

所以你需要把你的代码改成这样:

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

撰写回答