Forezz

Video_nn

Feb 13th, 2022
1,179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.53 KB | None | 0 0
  1. import cv2
  2. import os
  3. import sys
  4. import subprocess
  5. import glob
  6. from datetime import datetime
  7. from moviepy.editor import AudioFileClip
  8.  
  9. class VideoNN:
  10.     def improve_video(self, videofile, upd_videofile='untitled.avi', *args_realsr):#Function to improve the video
  11.         filename = videofile.split('/')[-1]#take filename
  12.         if upd_videofile.split('/')[-1].count('.') == 0:#check path it's file or directory
  13.             if not os.path.exists(upd_videofile):
  14.                 os.mkdir(upd_videofile)
  15.             directory = upd_videofile
  16.             upd_videofile += '/untitled.avi'#it's path for a future file
  17.         else:
  18.             directory = videofile.split(filename)[0]
  19.  
  20.         fragments_path = filename.replace('.', '-') + '_fragments'
  21.         upd_fragments_path = filename.replace('.', '-') + '_updated_fragments'
  22.         upd_videofile_WOA = 'UWOA_' + filename
  23.  
  24.         if directory:
  25.             fragments_path = directory + '/' + fragments_path
  26.             upd_fragments_path = directory + '/' + upd_fragments_path
  27.             upd_videofile_WOA = directory + '/' + upd_videofile_WOA
  28.         for path in [fragments_path, upd_fragments_path]:
  29.             if not os.path.exists(path):
  30.                 os.mkdir(path)
  31.         if self.video_to_fragments(videofile, fragments_path) != 0:
  32.             print('Error on function video to fragments')
  33.             return -1
  34.  
  35.         subprocess.run(['cp', fragments_path + '/info.txt', fragments_path + '/audio.mp3', upd_fragments_path])
  36.  
  37.         finish_returncode = self.use_realsr(fragments_path, upd_fragments_path, *args_realsr)
  38.  
  39.         if finish_returncode != 0:
  40.             print('Error on upscaling frames')
  41.             return -1
  42.  
  43.         if self.glue_frames(upd_fragments_path, upd_videofile_WOA) != 0:
  44.             print('Error on glue frames')
  45.             return -1
  46.         if self.add_audio(upd_videofile_WOA, fragments_path + '/audio.mp3', upd_videofile) != 0:
  47.             print('Error on adding audio')
  48.             return -1
  49.  
  50.         return 0
  51.  
  52.     def use_realsr(self, input_path, output_path, *args_realsr, realsr_path='./realsr-ncnn-vulkan/realsr-ncnn-vulkan'):
  53.         t1 = datetime.now()
  54.         finish = subprocess.run([realsr_path, '-i', input_path, '-o', output_path, *args_realsr])
  55.         t2 = datetime.now()
  56.         print('time cost realsr =', t2 - t1)
  57.         return finish.returncode
  58.  
  59.     def video_to_fragments(self, path, output_path=None):
  60.         # check paths
  61.         if not os.path.exists(path):
  62.             print(path + " not exists")
  63.             return
  64.         elif os.path.isdir(path):
  65.             print(path + " is not file")
  66.             return
  67.         elif output_path and output_path.split('/')[-1].count('.') > 0:
  68.             print(output_path + " is not directory")
  69.             return
  70.  
  71.         filename = path.split('/')[-1]
  72.  
  73.         if not output_path:
  74.             output_path = filename.replace('.', '-') + "_fragments"
  75.         if not os.path.exists(output_path):
  76.             os.mkdir(output_path)
  77.         if os.listdir(output_path):
  78.             print('WARNING!!! Path for fragments is not empty. Files with the same name will be overwritten')
  79.  
  80.         t1 = datetime.now()
  81.         videoCapture = cv2.VideoCapture()
  82.         videoCapture.open(path)
  83.         fps = videoCapture.get(cv2.CAP_PROP_FPS)
  84.         frames = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
  85.         print("fps=", int(fps), "frames=", int(frames))
  86.  
  87.         count_frames = 0 #sometimes the wrong number of frames is displayed. Recalculation just in case
  88.         for i in range(int(frames)):
  89.             ret, frame = videoCapture.read()
  90.             if ret:
  91.                 count_frames += 1
  92.                 cv2.imwrite("%s/%d.png" % (output_path, i), frame)
  93.         t2 = datetime.now()
  94.         if count_frames != frames:
  95.             frames = count_frames
  96.         print('time cost  = ', t2 - t1)
  97.  
  98.         # create a txt file with additional info for processing by other programs
  99.         with open(output_path + '/info.txt', 'w') as infoFile:
  100.             infoFile.write(str(int(fps)) + '\n')  # fps
  101.             infoFile.write(filename + '\n')  # filename
  102.             infoFile.write(str(int(frames)))  # frames
  103.         # catching audio
  104.         try:
  105.             audioclip = AudioFileClip(path)
  106.             audioclip.write_audiofile(output_path + '/audio.mp3')
  107.             audioclip.close()
  108.         except:
  109.             print('video without audio')
  110.  
  111.         return 0
  112.  
  113.     def glue_frames(self, src_path, videofile='untitled.avi', codec='h264', fps=30, *args_ffmpeg, photo_extenstion='png'):
  114.         frames = glob.glob(src_path + '/*.' + photo_extenstion)
  115.         if len(frames) == 0:
  116.             print(f'Frames with extension {photo_extenstion} not found')
  117.             return
  118.         # frameSize = cv2.imread(frames[0]).shape[1::-1]
  119.         filename = 'untitled.avi'
  120.  
  121.         if os.path.exists(src_path + '/info.txt'):
  122.             with open(src_path + '/info.txt', 'r') as infoFile:
  123.                 try:
  124.                     fps = int(infoFile.readline())
  125.                     filename = 'UpdWOA_' + infoFile.readline().strip()#Updated without audio
  126.                     count_frames = int(infoFile.readline())
  127.                     if count_frames != len(frames):
  128.                         print('The number of files in info.txt does not match the actual')
  129.                 except:
  130.                     print("Bad info.txt")
  131.         else:
  132.             print("WARNING!!! info.txt not exists. It's true path?")
  133.  
  134.         if videofile.split('/')[-1].count('.') == 0:
  135.             videofile += '/' + filename
  136.  
  137.         t1 = datetime.now()
  138.  
  139.         finish = subprocess.run(['ffmpeg', '-start_number', '1', '-r', str(fps), '-i', src_path + '/%d.png', '-vcodec', codec, '-y', *args_ffmpeg, videofile])
  140.  
  141.         t2 = datetime.now()
  142.         print('time cost qlue =', t2 - t1)
  143.  
  144.         return finish.returncode
  145.  
  146.     def add_audio(self, videofile, audio_path, new_name=None):
  147.         if not new_name:
  148.             new_name = 'UPDATED_' + videofile.split('/')[-1]
  149.         if videofile in (new_name, audio_path):
  150.             print('Files with same name')
  151.             return
  152.         t1 = datetime.now()
  153.         finish = subprocess.run(['ffmpeg', '-i', audio_path, '-i', videofile, '-codec', 'copy', '-y', new_name])
  154.         t2 = datetime.now()
  155.         print('time cost add audio = ', t2 -t1)
  156.         return finish.returncode
  157.  
  158. if __name__ == '__main__':
  159.     video_nn = VideoNN()
  160.     # video_nn.improveVideo('videos/crop_barabans.mp4', 'videos/cropped_fragments')
  161.     video_nn.improve_video(*sys.argv[1:])
Advertisement
Add Comment
Please, Sign In to add comment