Skip to content

Instantly share code, notes, and snippets.

@shivasiddharth
Last active September 1, 2023 22:06
Show Gist options
  • Save shivasiddharth/3ee632ce6513bc6ae956f58476983659 to your computer and use it in GitHub Desktop.
Save shivasiddharth/3ee632ce6513bc6ae956f58476983659 to your computer and use it in GitHub Desktop.
Script to upscale videos using OpenCV and ffmpeg
#!/usr/bin/env python
# Written by Shivasiddharth a.k.a Sid
# Youtube channel https://www.youtube.com/c/SidsEClassroom
# Share this script without removing the author's name
# This piece of script Upscales or Downscales videos using Opencv
# If the original video has an audio stream,
# it will merge the audio from the source file with the scaled video
# Usage: python3 videoupscaler.py -i "Sample.mp4" -o "Sample_Upscaled.mp4" -r 1920 1080
import cv2
import subprocess
from tqdm import tqdm
import sys
import argparse
def scale_video(sourcevideopath, upscaledvideopath, scalingresolution):
videosourcename = sourcevideopath
sourcevideo = cv2.VideoCapture(videosourcename)
destvideo = "Upscaled_Video.mp4"
sourcefps = sourcevideo.get(cv2.CAP_PROP_FPS)
totalframes = int(sourcevideo.get(cv2.CAP_PROP_FRAME_COUNT))
format = cv2.VideoWriter_fourcc(*'mp4v')
newresolution = scalingresolution
scaledvideo = cv2.VideoWriter(destvideo, format, sourcefps, newresolution)
print("")
print("Rescaling...........")
print("")
pbar = tqdm(total=totalframes)
while True:
ret, frame = sourcevideo.read()
if ret == True:
b = cv2.resize(frame,newresolution,fx=0,fy=0, interpolation = cv2.INTER_CUBIC)
scaledvideo.write(b)
pbar.update(1)
else:
pbar.close()
break
sourcevideo.release()
scaledvideo.release()
cv2.destroyAllWindows()
p = subprocess.Popen("ffprobe -show_streams -print_format json " + sourcevideopath, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
streams = p.communicate()[0]
streams = streams.decode('utf-8')
if 'audio' in streams.lower():
print("")
print("Extracting audio from source video.........")
print("")
subprocess.call("ffmpeg -i " + sourcevideopath + " sourceaudio.mp3", shell=True)
print("")
print("Merging source audio and upscaled video.........")
print("")
subprocess.call("ffmpeg -i " + destvideo + " -i sourceaudio.mp3 -map 0:0 -map 1:0 " + upscaledvideopath, shell=True)
else:
print("")
print("No audio stream found.........")
print("")
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', type=str,
metavar='Source video path', required=True,
help='Path to source file.')
parser.add_argument('-o', type=str,
metavar='Scaled video path', required=True,
help='Path to scaled file.')
parser.add_argument('-r', type=int, nargs='+',
metavar='Desired video resolution', required=True,
help='Desired video output resolution.')
args = parser.parse_args()
if not args.i and not i:
raise Exception('Missing -i Input option')
if not args.o and not o:
raise Exception('Missing -o Output option')
if not args.r and not r:
raise Exception('Missing -r Resolution option')
scale_video(args.i, args.o, tuple(args.r))
@ABDERRAHMANE-OUALI
Copy link

I tried to up scale a 144p video to 720p and it didn't work the video file just got bigger in size with no quality changes at all

@TheHimanshuRastogi
Copy link

TheHimanshuRastogi commented Dec 24, 2022

I tried to up scale a 144p video to 720p and it didn't work the video file just got bigger in size with no quality changes at all

It was because a 144p video is a very low resolution while cv2 just upscales (increases width & height and maintains aspect ratio) each frame one by one and it has nothing to do with enhancing quality, if you want to improve the quality of a video, for example, restoring an old video, then you should consider some AI software that enhances the quality of each frame one by one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment