import sys
import os
import vvdutils as vv
import cv2 class Compress_Pic_or_Video(object):
def __init__(self):
pass
def is_video(self, file_path):
videoSuffixSet = {"WMV","ASF","ASX","RM","RMVB","MP4","3GP","MOV","M4V","AVI","DAT","MKV","FIV","VOB"}
suffix = vv.get_suffix(file_path).upper()
if suffix in videoSuffixSet:
return True
else:
return False
def infer_video_file(self, file_path, delete_origin_file=False):
if not self.is_video(file_path):
return
else:
width, height = self.get_target_size(file_path)
self.SaveVideo(file_path, width, height, delete_origin_file)
def get_target_size(self, file_path):
cap = cv2.VideoCapture(file_path)
cap.set(1, 1) # 取它的第一帧
rval, frame = cap.read() # 如果rval为False表示这个视频有问题,为True则正常
cap.release()
height = frame.shape[0] # 高度
width = frame.shape[1] # 宽度
max_size = 1280
factor = min(1, max_size / max(height, width))
width = int(width * factor // 2 * 2)
height = int(height * factor // 2 * 2)
return width, height
def SaveVideo(self, file_path, width, height, delete_origin_file=False):
print('width', width, 'height', height)
fpsize = os.path.getsize(file_path) / 1024
file_path = file_path.replace(' ', '\ ')
file_path = file_path.replace('(', '\(')
file_path = file_path.replace(')', '\)')
dir_path= vv.OS_dirname(file_path)
stem = vv.get_path_stem(file_path)
output_path = vv.OS_join(dir_path, stem + '_compress.mp4')
print(f"file path: {file_path}")
print(f"output path: {output_path}")
if fpsize >= 150.0: # 大于150KB的视频需要压缩
compress = "ffmpeg -y -i {} -r 12 -s {}x{} -b:v 200k {}".format(file_path, width, height, output_path)
isRun = os.system(compress)
if isRun != 0:
return (isRun,"没有安装ffmpeg")
else:
if delete_origin_file:
vv.remove_file(file_path)
return True
else:
return True
if __name__ == "__main__":
b = sys.argv
try:
dir_path = b[1]
except:
dir_path = '.'
comp_obj = Compress_Pic_or_Video()
mp4_file_path_list = vv.glob_videos(dir_path)
for file_path in vv.tqdm(mp4_file_path_list):
if '_compress.mp4' not in file_path:
try:
comp_obj.infer_video_file(file_path, True)
except Exception as e:
print(e)
print(f" !! Video {file_path} is error. ")