1. 視頻的讀取
主要使用python的cv2
主要介紹:視頻幀讀取、視頻寬高讀取、FPS讀取
import cv2 as cv
vc = cv.VideoCapture('12.mp4') # 讀入視頻文件
fps=vc.get(cv.CAP_PROP_FPS) #獲取fps
size = (int(vc.get(cv.CAP_PROP_FRAME_WIDTH)),int(vc.get(cv.CAP_PROP_FRAME_HEIGHT))) #獲取寬高
rval, frame = vc.read()
while(rval):
rval, frame = vc.read() # 循環讀取每一視頻幀
2. 視頻的保存
1)PIL
給圖片視頻上添加矩形框、文字
from PIL import Image, ImageFont, ImageDraw
img_draw= Image.open(filename) #返回一個Image對象
img_draw.show()
draw = ImageDraw.Draw(img_draw)
draw.rectangle((x,y,h,w), width=5)
fontpath = "font/simsun.ttc"
font = ImageFont.truetype(fontpath, 32)
draw.text((x,y)), '你好', font=font, fill=(255, 255, 255))
draw.save(outfile)
2) CV2
將所需的視頻幀進行保存成視頻形式
提取音頻形式
將視頻配上音頻
import subprocess
import cv2 as cv
def video2mp3(file_name):
"""
將視頻轉爲音頻
:param file_name: 傳入視頻文件的路徑
:return:
"""
outfile_name = file_name.split('.')[0] + '.mp3'
subprocess.call('ffmpeg -i ' + file_name
+ ' -f mp3 ' + outfile_name, shell=True)
def video_add_mp3(file_name, mp3_file):
"""
視頻添加音頻
:param file_name: 傳入視頻文件的路徑
:param mp3_file: 傳入音頻文件的路徑
:return:
"""
outfile_name = file_name.split('.')[0] + '-txt.mp4'
subprocess.call('ffmpeg -i ' + file_name
+ ' -i ' + mp3_file + ' -strict -2 -f mp4 '
+ outfile_name, shell=True)
def save_new_video(file_name):
""" 將視頻幀保存
:param file_name: 傳入視頻文件的路徑
:return:
"""
outfile_name = 'new_'+file_name.split('.')[0] + '.mp4'
vc = cv.VideoCapture(file_name)
interval=vc.get(cv.CAP_PROP_FPS)
fourcc = cv.VideoWriter_fourcc(*"mp4v")
size = (int(vc.get(cv.CAP_PROP_FRAME_WIDTH)),int(vc.get(cv.CAP_PROP_FRAME_HEIGHT)))
out = cv.VideoWriter(outfile_name, fourcc, interval, size)
rval, frame = vc.read()
while(rval):
out.write(frame)
rval, frame = vc.read()
vc.release()
out.release()
if __name__ == '__main__':
# video2mp3(file_name='MyVideo_3.mp4')
#save_new_video(file_name='MyVideo_3.mp4')
video_add_mp3(file_name='new_MyVideo_3.mp4', mp3_file='MyVideo_3.mp3')