python提取视频第一帧图片

一.实现代码

# -*- coding: utf-8 -*-
import cv2
from PIL import Image
from io import BytesIO

def tryTime(maxTry, timeout=random.random()):
    """
    重试
    :param maxTry:重试次数
    :param timeout:睡眠时间
    :return:
    """
    def wrap1(func):
        #functools.wraps 可以将原函数对象的指定属性复制给包装函数对象,
        @functools.wraps(func)
        def __decorator(*args,**kwargs):
            tryTime = 0
            while tryTime < maxTry:
                try:
                    return func(*args,**kwargs)
                except Exception:
                    pass
                    # print("TryTime_except==%s"%traceback.format_exc())
                    # logDebug("tryTime","TryTime_except==%s"%traceback.format_exc())
                tryTime += 1
                time.sleep(timeout)
        return __decorator
    return wrap1

@tryTime(2)
def get_video_cover(url):
    cap = cv2.VideoCapture(url)
    rate = cap.get(5)
    frame_number = cap.get(7)  # 视频文件的帧数
    if rate==0:
        duration=0
    else:
        duration = int(frame_number / rate)  # 单位秒
    cap.set(1, 1)  # 取它的第一帧
    rval, frame = cap.read()  # 如果rval为False表示这个视频有问题,为True则正常
    data = cv2.imencode(".jpg", frame)[1].tobytes()  # 将图片转为jpg格式的二进制流
    cap.release()
    height = frame.shape[0]  # 高度
    width = frame.shape[1]  # 宽度
    return data, duration, width, height


def get_image_size(data):
    im = Image.open(BytesIO(data))
    return im.size



posted @ 2020-09-29 15:07  小小咸鱼YwY  阅读(2806)  评论(0编辑  收藏  举报