opencv处理过视频后没有声音,通过ffmpeg包对视频的音频和视频进行分离与合并
import cv2
import numpy as np
from ffmpy3 import FFmpeg
class do_audio_class(object):
def __init__(self):
self.logo_path = '*.png'
self.logo_path_pc = '*.png'
def save_logo(self, img):
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(9, 9))
mask = cv2.morphologyEx(img[-110:, -210:, :], cv2.MORPH_TOPHAT, kernel)
mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
ret, dst = cv2.threshold(mask_gray, 50, 255, cv2.THRESH_BINARY)
dilate_kernel = np.ones((10,10), np.uint8)
dilate_mask = cv2.dilate(dst, dilate_kernel, iterations=1)
cv2.imwrite(self.logo_path, dilate_mask)
def do_erode(self, img):
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(30, 30))
img[-110:, -210:, :] = cv2.erode(img[-110:, -210:, :], kernel, iterations=1)
return img
def do_inpaint(self, img):
mask_gray = cv2.imread(self.logo_path_pc, 0) #读取灰度图像
#img[-110:, -210:, :] = cv2.inpaint(img[-110:, -210:, :], mask_gray, 3, cv2.INPAINT_TELEA)
#pc图片修复
img[-50:, -100:, :] = cv2.inpaint(img[-50:, -100:, :], mask_gray, 3, cv2.INPAINT_TELEA)
return img
def performaudio(video_path, output_audio_path):
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(output_audio_path, fourcc, fps, (width, height))
do_audio = do_audio_class()
i = 0
while (cap.isOpened()):
ret, frame = cap.read()
if not ret:# or i > (count - 80): #80
break
do_audio_img = do_audio.do_inpaint(frame)
#cv2.imshow('do_audio_img', do_audio_img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
#exit()
out.write(do_audio_img)
i = i + 1
cap.release()
out.release()
cv2.destroyAllWindows()
#音视频分离
def open_audio_video(mp4_file_path, video_path, audio_path):
ff = FFmpeg(
inputs={mp4_file_path:None},
outputs={
audio_path:['-map', '0:0', '-c:a', 'copy', '-f', 'mp4'],
video_path:['-map', '0:1', '-c:a', 'copy', '-f', 'mp4']
}
)
ff.run()
#音视频合并
def close_audio_video(out_mp4_file_path, video_path, audio_path):
ff = FFmpeg(
inputs={
audio_path:None,
video_path:None
},
outputs={out_mp4_file_path:'-c:v h264 -c:a aac'}
)
ff.run()
if __name__ == "__main__":
mp4_file_path = 'D:/opencvtest/opencvtest.mp4'
video_path = 'D:/opencvtest/video.mp4'
audio_path = 'D:/opencvtest/audio.mp4'
output_audio_path = 'D:/opencvtest/output.mp4'
out_mp4_file_path = 'D:/opencvtest/newout.mp4'
open_audio_video(mp4_file_path, video_path, audio_path)
performaudio(audio_path, output_audio_path)
close_audio_video(out_mp4_file_path, video_path, output_audio_path)