ffmpeg根據時間獲取視頻圖片,並解析標籤結果

import ffmpeg
import numpy
import cv2
import sys
import json



def read_frame_by_time(in_file, time):
    """
    指定時間節點讀取任意幀
    """
    out, err = (
        ffmpeg.input(in_file, ss=time)
            .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
            .run(capture_stdout=True)
    )
    return out


def get_video_info(in_file):
    """
    獲取視頻基本信息
    """
    try:
        probe = ffmpeg.probe(in_file)
        video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
        if video_stream is None:
            print('No video stream found', file=sys.stderr)
            sys.exit(1)
        return video_stream
    except ffmpeg.Error as err:
        print(str(err.stderr, encoding='utf8'))
        sys.exit(1)
def init_mark_result(mark_result):
    txt = json.load(open(mark_result,encoding= 'utf-8'))['markData']
    print(len(txt))
    txt = [item for item in txt if 'currentKey' in item]
    txts = sorted(txt,key=lambda x:x['currentKey'])
    return txts

if __name__ == '__main__':
    result_path = '/Users/xxx/Downloads/10324-1.txt'
    file_path = '/Users/xxxx/Downloads/xingren20200508_ch0007_00000001056000000_0.mp4'
    txts = init_mark_result(result_path)
    print(len(txts))
    for txt in txts:
        sss = (int(txt['currentKey']) - 10*25*40) / 1000.0
        if sss < 0:
            sss = 0
        print(sss)
        print(txt['data'])
        frame_boxs = txt['data']
        out = read_frame_by_time(file_path, sss)
        image_array = numpy.asarray(bytearray(out), dtype="uint8")
        image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
        for box in frame_boxs:
            x = box['x']
            y = box['y']
            w = box['width']
            h = box['height']
            print('========')
            print(box['userSelectedValue']['multiValue'][0]['parentId'])
            print(box['userSelectedValue']['firstId'])
            color = (0, 0, 255)
            cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), color, 2)
        cv2.imshow('frame', image)
        cv2.waitKey(1000)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章