python-opencv消除视频中的黑色闪频
# -*- coding =utf-8 -*-
# @Time :2022/4/17 21:05
# @Author :clerk
# @File :消除视频黑屏.py
# @Software :PyCharm
import uuid
from ffmpy import FFmpeg
from moviepy.editor import *
import cv2
# 提取音频
def get_audio(input_path: str, audio_out_path: str):
audio = AudioFileClip(input_path)
audio.write_audiofile(audio_out_path)
# 消除黑屏
def getout_blck(input_path: str, movie_out_path: str):
capture = cv2.VideoCapture(input_path)
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
fps = capture.get(cv2.CAP_PROP_FPS) # 获取原视频fps值
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) # 获取原视频的高度和宽度
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter(movie_out_path, fourcc, fps, (width, height), True)
i = 0
if capture.isOpened(): # 检测摄像头是否打开
while True:
i += 1
ret, img_src = capture.read()
if not ret:
break
# 查看黑图(利用从cv2.cvtColor转为灰度图,得到暗值判断是否为黑图)
gray_img = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY) # 获取灰度图矩阵的行数和列数
r, c = gray_img.shape[:2]
piexs_sum = r * c # 整个弧度图的像素个数为r*c
# 获取偏暗的像素(表示0~19的灰度值为暗) 此处阈值可以修改
dark_points = (gray_img < 20)
target_array = gray_img[dark_points]
dark_sum = target_array.size
# 判断灰度值为暗的百分比
dark_prop = dark_sum / piexs_sum
if i == 1:
writer.write(img_src)
elif dark_prop >= 0.85:
writer.write(img_out)
continue # 若为黑图则替换为上一帧图片
else:
writer.write(img_src)
img_out = img_src
else:
print('视频打开失败')
print("消除完成")
writer.release()
# 音频和视频结合
def audio_add_movie(movie_out_path: str, audio_out_path: str, dir_path: str):
_ext_video = os.path.basename(movie_out_path).strip().split('.')[-1]
_ext_audio = os.path.basename(audio_out_path).strip().split('.')[-1]
if _ext_audio not in ['mp3', 'wav']:
raise Exception('audio format not support')
_codec = 'copy'
if _ext_audio == 'wav':
_codec = 'aac'
result = os.path.join(dir_path, '{}.{}'.format(uuid.uuid4(), _ext_video))
ff = FFmpeg(executable="D:/测试/EVCapture/ffmpeg.exe",
inputs={movie_out_path: None, audio_out_path: None},
outputs={
result: '-map 0:v -map 1:a -c:v copy -c:a {} -shortest'.format(_codec)}) # executable中为ffmpeg.exe路径
ff.run()
def main():
input_path = "C:/测试/test.mp4" # 原视频路径
audio_out_path = "C:/测试/test.mp3" # 音频路径
movie_out_path = "C:/测试/clean.mp4" # 消除黑屏视频后路径
dir_path = "C:/测试/" # 保存路径
get_audio(input_path, audio_out_path)
getout_blck(input_path, movie_out_path)
audio_add_movie(movie_out_path, audio_out_path, dir_path)
if __name__ == "__main__":
main()
print("完成")
其中 若是原视频文件后缀为avi,fourcc=cv2.VideoWriter_fourcc(*‘XVID’)