Creating a Python script that fully enhances a video by removing blurriness and noise, maintaining color fidelity, and upscaling it to 4K resolution quickly while showing progress is a complex task. It involves advanced video processing, super-resolution, denoising, and color correction techniques, which are computationally expensive.
However, I can provide a practical, optimized solution using state-of-the-art libraries that balance speed and quality:
- OpenCV for video reading/writing and basic processing.
- Real-ESRGAN (a fast and high-quality super-resolution model) for upscaling.
- Fast denoising with OpenCV's fastNlMeansDenoisingColored.
- Color preservation by working in the right color space.
- TQDM for progress bar.
- Tkinter for file browsing.
Important Notes:
- Real-ESRGAN requires a GPU (CUDA) for fast processing. CPU is possible but slow.
- Upscaling to 4K (3840x2160) is very resource-intensive.
- Full blur removal is tricky; we do denoising + sharpening.
- This script will process frame-by-frame, showing progress.
- You must install dependencies and download Real-ESRGAN weights.
Step 1: Install dependencies
pip install opencv-python tqdm tkinter realesrgan
Note: realesrgan Python package is a wrapper for Real-ESRGAN models. Alternatively, you can use the official Real-ESRGAN repo or torch + realesrgan models manually.
Step 2: Full Python code
import cv2
import numpy as np
import time
from tqdm import tqdm
from tkinter import Tk, filedialog
from realesrgan import RealESRGAN
import torch
def browse_file():
root = Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title="Select Video File",
filetypes=[("Video files", "*.mp4 *.avi *.mkv *.mov")])
return file_path
def denoise_and_sharpen(frame):
# Denoise color image
denoised = cv2.fastNlMeansDenoisingColored(frame, None, h=10, hColor=10, templateWindowSize=7, searchWindowSize=21)
# Sharpen image using kernel
kernel = np.array([[0, -1, 0],
[-1, 5,-1],
[0, -1, 0]])
sharpened = cv2.filter2D(denoised, -1, kernel)
return sharpened
def main():
# Browse video file
video_path = browse_file()
if not video_path:
print("No file selected, exiting.")
return
# Open video
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print("Error opening video file.")
return
# Get video properties
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Target resolution 4K
target_width, target_height = 3840, 2160
# Initialize Real-ESRGAN model (use GPU if available)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Using device: {device}")
model = RealESRGAN(device, scale=4) # 4x upscaling
model.load_weights('RealESRGAN_x4.pth') # Make sure you have this weight file in your working directory
# Output video writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
output_path = video_path.rsplit('.', 1)[0] + '_enhanced_4k.mp4'
out = cv2.VideoWriter(output_path, fourcc, fps, (target_width, target_height))
start_time = time.time()
print("Processing video...")
for i in tqdm(range(frame_count), desc="Enhancing frames"):
ret, frame = cap.read()
if not ret:
break
# Denoise and sharpen
enhanced = denoise_and_sharpen(frame)
# Upscale using Real-ESRGAN
# Real-ESRGAN expects RGB images
rgb = cv2.cvtColor(enhanced, cv2.COLOR_BGR2RGB)
upscaled = model.predict(rgb)
# Convert back to BGR for OpenCV
upscaled_bgr = cv2.cvtColor(upscaled, cv2.COLOR_RGB2BGR)
# Resize to exact 4K if needed (Real-ESRGAN x4 might not be exactly 4K)
upscaled_bgr = cv2.resize(upscaled_bgr, (target_width, target_height), interpolation=cv2.INTER_LANCZOS4)
# Write frame
out.write(upscaled_bgr)
# Estimate time left
elapsed = time.time() - start_time
avg_time_per_frame = elapsed / (i + 1)
frames_left = frame_count - (i + 1)
time_left = frames_left * avg_time_per_frame
print(f"\rProgress: {((i+1)/frame_count)*100:.2f}% - Estimated time left: {time_left:.1f}s", end='')
print("\nProcessing complete.")
cap.release()
out.release()
print(f"Enhanced video saved to: {output_path}")
if __name__ == "__main__":
main()
How this works:
- File browsing: Opens a dialog to select your video.
- Denoising + sharpening: Removes noise and enhances edges.
- Upscaling: Uses Real-ESRGAN x4 model to upscale frames.
- Color: Maintains color by converting between BGR and RGB properly.
- Progress: Shows progress bar and estimated time left.
- Output: Saves enhanced 4K video automatically.
What you need to do:
-
Download the Real-ESRGAN x4 weights from the official repo:
https://github.com/xinntao/Real-ESRGAN/releases
Place RealESRGAN_x4.pth in your working directory.
-
Run the script.
Limitations & Tips:
- Speed: Real-ESRGAN on GPU is fast but still takes time for long videos.
- CPU: If no GPU, processing will be slow.
- Memory: Upscaling 4K videos requires a lot of RAM and VRAM.
- Improvements: You can batch process frames or use multi-threading for speed but it complicates code.
If you want a lighter but less powerful version without Real-ESRGAN, I can provide that too. Let me know!