1

我正在运行以下代码将视频转换为帧。问题是它正在创建大小为 0 KB 的图像文件,当我打开它时没有显示任何内容。我不明白是什么造成了问题。我需要安装任何图像编解码器吗?

    '''
    Using OpenCV takes a mp4 video and produces a number of images. I am using OpenCV 3.3.0 version and Python 2.7


    Which will produce a folder called data with the images, There will be 2000+ images for example.mp4.
    '''
    import cv2
import numpy as np
import os

# Playing video from file:

try:
        cap = cv2.VideoCapture('aa.mkv')
except:
        print "Could not open video file"
        raise
print cap.grab()

try:
    if not os.path.exists('data'):
        os.makedirs('data')
except OSError:
    print ('Error: Creating directory of data')

currentFrame = 0
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    if not frame is None:
        # Saves image of the current frame in jpg file
        name = './data/frame' + str(currentFrame) + '.jpg'
        print ('Creating...' + name)
        cv2.imwrite(name, frame)
        #cv2.imshow(name, frame)
    else:
        break

    # To stop duplicate images
    currentFrame += 1

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
4

1 回答 1

3

您没有使用 imwrite 函数来写入帧。此外,您的 imshow 函数名称拼写错误。我已经对您的代码进行了更改。试试这个:

import cv2
import numpy as np
import os

# Playing video from file:
cap = cv2.VideoCapture('aa.mkv')

try:
    if not os.path.exists('data'):
        os.makedirs('data')
except OSError:
    print ('Error: Creating directory of data')

currentFrame = 0
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    if not frame is None:
        # Saves image of the current frame in jpg file
        name = './data/frame' + str(currentFrame) + '.jpg'
        print ('Creating...' + name)
        cv2.imwrite(name, frame)
        cv2.imshow(name, frame)
    else:
        break

    # To stop duplicate images
    currentFrame += 1

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
于 2017-09-21T01:51:28.750 回答