解决Python OpenCV 读取视频并抽帧出现error while decoding的问题

解决Python OpenCV 读取视频抽帧出现error while decoding的问题

    • 1. 问题
    • 2. 解决
    • 3. 源代码
    • 参考

1. 问题

读取H264视频,抽帧视频并保存,报错如下;

[aac @ 00000220b9a07fc0] Input buffer exhausted before END element found
[h264 @ 00000220b9cd0500] error while decoding MB 20 45, bytestream -14

2. 解决

溯本求源:https://stackoverflow.com/questions/49233433/opencv-read-errorh264-0x8f915e0-error-while-decoding-mb-53-20-bytestream

发现问题原因是:它与时间有关,当在连续的capture.read()之间执行比较耗时的操作时会出现该错误。

解决:增加一个线程处理捕获到的视频帧就好~~~

3. 源代码

import os
import queue
import threading

import cv2

q = queue.Queue()
save_path = ''


def get_frame_from_video(video_name, interval):
    """
    Args:
        video_name:输入视频名字
        interval: 保存图片的帧率间隔
    Returns:
    """
    # 开始读视频
    video_capture = cv2.VideoCapture(video_name)
    i = 0

    while True:
        success, frame = video_capture.read()

        # 检测是否到了视频尾部
        if not success or frame is None:
            print('video is all read')
            break
        i += 1
        if i % interval == 0:
            q.put(frame)


def Display(arr):
    print("Start Displaying")
    j = int(arr)
    while True:
        if q.empty() != True:
            frame = q.get()
            # 保存图片
            j += 1
            save_name = save_path + str(j) + '.jpg'
            cv2.imwrite(save_name, frame)
            print('image of %s is saved' % save_name)
            # cv2.imshow(save_name, frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

if __name__ == '__main__':
    video_name = 'F:\\v01.H264'
    j = 0
    save_path = video_name.split('.H264')[0] + "\\"
    print(save_path)
    interval = 125
    # 保存图片的路径
    is_exists = os.path.exists(save_path)
    if not is_exists:
        os.makedirs(save_path)
        print('path of %s is build' % save_path)

    p2 = threading.Thread(target=Display,args=[j])
    p2.start()
    get_frame_from_video(video_name, interval)

参考

  • https://stackoverflow.com/questions/49233433/opencv-read-errorh264-0x8f915e0-error-while-decoding-mb-53-20-bytestream
  • https://blog.csdn.net/darkeyers/article/details/84865363

你可能感兴趣的:(Python,OpenCV,Python,图像处理,python,opencv,计算机视觉,视频抽帧图片保存)