File size: 2,013 Bytes
ad42b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import cv2
import tempfile
import os

def process_video(video_path):
    # Open the video file
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return None

    # Create a temporary file to save the processed video
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
    output_path = temp_file.name

    # Get video properties
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = int(cap.get(cv2.CAP_PROP_FPS))

    # Define the codec and create a VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height), isColor=False)

    # Process each frame
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        # Convert the frame to grayscale (example processing)
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Write the processed frame to the output video
        out.write(gray_frame)

    # Release everything
    cap.release()
    out.release()

    return output_path

def preview_video(video):
    # Save the uploaded video to a temporary file
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
    temp_path = temp_file.name
    with open(temp_path, "wb") as f:
        f.write(video)

    # Process the video using OpenCV
    processed_video_path = process_video(temp_path)

    # Clean up the temporary file
    os.unlink(temp_path)

    return processed_video_path

# Define the Gradio interface
iface = gr.Interface(
    fn=preview_video,  # Function to call
    inputs=gr.Video(label="Upload Video"),  # Input component: Video upload
    outputs=gr.Video(label="Preview Video"),  # Output component: Video preview
    title="Video Preview with OpenCV",
    description="Upload a video, and it will be processed (e.g., grayscale) and displayed."
)

# Launch the interface
iface.launch()