python ffmpeg任意提取视频帧的方法
环境准备
1、安装FFmpeg
音/视频工具FFmpeg简易安装文档
2、安装ffmpeg-python
pip3installffmpeg-python
3、【可选】安装opencv-python
pip3installopencv-python
4、【可选】安装numpy
pip3installnumpy
视频帧提取
准备视频素材
抖音视频素材下载:https://anoyi.com/dy/top
基于视频帧数提取任意一帧
importffmpeg
importnumpy
importcv2
importsys
importrandom
defread_frame_as_jpeg(in_file,frame_num):
"""
指定帧数读取任意帧
"""
out,err=(
ffmpeg.input(in_file)
.filter('select','gte(n,{})'.format(frame_num))
.output('pipe:',vframes=1,format='image2',vcodec='mjpeg')
.run(capture_stdout=True)
)
returnout
defget_video_info(in_file):
"""
获取视频基本信息
"""
try:
probe=ffmpeg.probe(in_file)
video_stream=next((streamforstreaminprobe['streams']ifstream['codec_type']=='video'),None)
ifvideo_streamisNone:
print('Novideostreamfound',file=sys.stderr)
sys.exit(1)
returnvideo_stream
exceptffmpeg.Erroraserr:
print(str(err.stderr,encoding='utf8'))
sys.exit(1)
if__name__=='__main__':
file_path='/Users/admin/Downloads/拜无忧.mp4'
video_info=get_video_info(file_path)
total_frames=int(video_info['nb_frames'])
print('总帧数:'+str(total_frames))
random_frame=random.randint(1,total_frames)
print('随机帧:'+str(random_frame))
out=read_frame_as_jpeg(file_path,random_frame)
image_array=numpy.asarray(bytearray(out),dtype="uint8")
image=cv2.imdecode(image_array,cv2.IMREAD_COLOR)
cv2.imshow('frame',image)
cv2.waitKey()
基于时间提取任意一帧
importffmpeg
importnumpy
importcv2
importsys
importrandom
defread_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)
)
returnout
defget_video_info(in_file):
"""
获取视频基本信息
"""
try:
probe=ffmpeg.probe(in_file)
video_stream=next((streamforstreaminprobe['streams']ifstream['codec_type']=='video'),None)
ifvideo_streamisNone:
print('Novideostreamfound',file=sys.stderr)
sys.exit(1)
returnvideo_stream
exceptffmpeg.Erroraserr:
print(str(err.stderr,encoding='utf8'))
sys.exit(1)
if__name__=='__main__':
file_path='/Users/admin/Downloads/拜无忧.mp4'
video_info=get_video_info(file_path)
total_duration=video_info['duration']
print('总时间:'+total_duration+'s')
random_time=random.randint(1,int(float(total_duration))-1)+random.random()
print('随机时间:'+str(random_time)+'s')
out=read_frame_by_time(file_path,random_time)
image_array=numpy.asarray(bytearray(out),dtype="uint8")
image=cv2.imdecode(image_array,cv2.IMREAD_COLOR)
cv2.imshow('frame',image)
cv2.waitKey()
相关资料
https://github.com/kkroening/ffmpeg-python/tree/master/examples
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。