deblur / app.py
bcci's picture
Create app.py
202725c verified
import os
import cv2
import numpy as np
from PIL import Image, ImageEnhance
from tqdm import tqdm
import gradio as gr
import tempfile
def enhance_frame(frame, sharpness=4, contrast=1.1, blur=3):
"""Enhance a video frame's sharpness, contrast, and blur."""
try:
# Convert the frame to RGB (if it's in BGR format)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Convert the frame to PIL Image
pil_img = Image.fromarray(frame)
# Enhance the sharpness
enhancer = ImageEnhance.Sharpness(pil_img)
enhanced_frame = enhancer.enhance(sharpness)
# Enhance the contrast
enhancer = ImageEnhance.Contrast(enhanced_frame)
enhanced_frame = enhancer.enhance(contrast)
# Convert back to numpy array
enhanced_frame = np.array(enhanced_frame)
# Apply Gaussian blur
enhanced_frame = cv2.GaussianBlur(enhanced_frame, (blur, blur), 0)
# Convert back to BGR format for OpenCV
enhanced_frame = cv2.cvtColor(enhanced_frame, cv2.COLOR_RGB2BGR)
return enhanced_frame
except Exception as e:
raise ValueError(f"Error enhancing frame: {str(e)}")
def enhance_video(input_path, output_path, sharpness=4, contrast=1.3, blur=3):
"""Enhance a video's sharpness, contrast, and blur."""
try:
# Open the video file
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
raise ValueError("Error: Could not open video file.")
# Get video properties
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
raise ValueError("Error: Video file has no frames.")
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Using mp4v codec for mp4 files
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
if not out.isOpened():
cap.release()
raise ValueError("Error: Could not open video writer.")
# Process each frame with tqdm progress bar
for _ in tqdm(range(total_frames), desc="Processing frames"):
ret, frame = cap.read()
if not ret:
break
# Enhance the frame
enhanced_frame = enhance_frame(frame, sharpness, contrast, blur)
# Write the enhanced frame to the output video
out.write(enhanced_frame)
# Release everything when done
cap.release()
out.release()
except Exception as e:
if 'cap' in locals():
cap.release()
if 'out' in locals():
out.release()
raise ValueError(f"Error enhancing video: {str(e)}")
def video_enhancer(input_video, sharpness=4, contrast=1.3, blur=3):
"""Gradio interface function to enhance videos."""
try:
# Check if input file exists
if not os.path.exists(input_video):
raise FileNotFoundError("Input video file not found.")
# Generate a temporary output path
temp_dir = tempfile.gettempdir()
base_name = os.path.basename(input_video)
name, ext = os.path.splitext(base_name)
output_path = os.path.join(temp_dir, f"enhanced_{name}.mp4")
# Process the video
enhance_video(input_video, output_path, sharpness, contrast, blur)
return output_path
except Exception as e:
return f"Error: {str(e)}"
# Create the Gradio interface
iface = gr.Interface(
fn=video_enhancer,
inputs=[
gr.Video(label="Upload Video"),
gr.Slider(minimum=1, maximum=10, value=4, label="Sharpness"),
gr.Slider(minimum=0.5, maximum=2, step=0.1, value=1.1, label="Contrast"),
gr.Slider(minimum=1, maximum=10, step=0.1, value=3, label="Blur")
],
outputs=gr.Video(label="Download Enhanced Video"),
title="Video Enhancer",
description="Enhance your videos by adjusting sharpness, contrast, and blur."
)
iface.launch()