1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| 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() 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: 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. ")
|