
▶ 環境准備
1、安裝 FFmpeg
2、安裝 ffmpeg-python
pip3 install ffmpeg-python
3、【可選】安裝 opencv-python
pip3 install opencv-python
4、【可選】安裝 numpy
pip3 install numpy
▶ 視頻幀提取
准備視頻素材
抖音視頻素材下載:https://anoyi.com/dy/top
基於視頻幀數提取任意一幀
import ffmpeg
import numpy
import cv2
import sys
import random
def read_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)
)
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)
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()
基於時間提取任意一幀
import ffmpeg
import numpy
import cv2
import sys
import random
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)
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()
▶ 相關資料
本文由博客一文多發平台 OpenWrite 發布!
