python ffmpeg 获取视频信息_opencv和ffmpeg查询视频信息(python)

1. 用Opencv获取

def get_source_info_opencv(source_name):

return_value = 0

try:

cap = cv2.VideoCapture(source_name)

width = cap.get(cv2.CAP_PROP_FRAME_WIDTH )

height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

fps = cap.get(cv2.CAP_PROP_FPS)

num_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)

return_value = {"width" : int(width),

"height": int(height),

"num_frames": int(num_frames),

"fps" : int(fps) if not fps == float('inf') else 15}

# print("width:{} \nheight:{} \nfps:{} \nnum_frames:{}".format(width, height, fps, num_frames))

# show_statisrics(source_name, fps, width, height, num_frames)

except (OSError, TypeError, ValueError, KeyError, SyntaxError) as e:

print("init_source:{} error. {}\n".format(source_name, str(e)))

return_value = -1

return return_value

2. 用ffmpeg获取

注意python运行如下代码有两个条件:

pip install ffmpeg-opencv

在系统安装或者编译ffmpeg(windows、linux、macos)

def get_source_info_ffmpeg(source_name):

return_value = 0

assert os.path.exists(source_name)

try:

info = ffmpeg.probe(source_name)

# print(info)

# print("---------------------------------")

vs = next(c for c in info['streams'] if c['codec_type'] == 'video')

format_name = info['format']['format_name']

codec_name = vs['codec_name']

duration_ts = float(vs['duration_ts'])

fps = int(vs['r_frame_rate'][:-2])

width = vs['width']

height = vs['height']

duration = int(float(vs['duration']))

# 如果只用ffmpeg,這裡不應該使用Opencv

cap = cv2.VideoCapture(source_name)

num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if cap.get(cv2.CAP_PROP_FRAME_COUNT) else \

duration * fps

return_value = {"width": width,

"height": height,

"num_frames": duration * fps ,

"fps": int(fps)}

show_statisrics(source_name, fps, width, height, num_frames)

# print("format_name:{} \ncodec_name:{} \nduration_ts:{} \nwidth:{} \nheight:{} \nfps:{}".format(format_name, codec_name, duration_ts, width, height, fps))

except (OSError, TypeError, ValueError, KeyError, SyntaxError) as e:

print("init_source:{} error. {}\n".format(source_name, str(e)))

return_value = 0

return return_value

3. 信息打印

def show_statisrics(source_name, fps, width, height, num_frames):

print("Video statistics:")

print(" ----------------------------------------")

print(" Items | Info ")

print(" ----------------------------------------")

print(" Path | {:>20s} ".format(source_name) )

print(" width | {:20d} ".format(width) )

print(" height | {:20d} ".format(height) )

print(" num_frames | {:20d} ".format(num_frames) )

print(" fps | {:>20d} ".format(fps) )

print(" ----------------------------------------")

效果如下:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值