previews / preview_test.py
SPACERUNNER99's picture
Upload preview_test.py
4d647f3 verified
raw
history blame
1.6 kB
import gradio as gr
import cv2
def extract_frames(video_path):
# Open the video file
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
# If video cannot be opened, return four None values
return [None] * 4
# Get the total number of frames
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
# If video has no frames, release and return None values
cap.release()
return [None] * 4
# Calculate frame indices at 0%, 25%, 50%, and 75%
indices = [int(total_frames * i / 4) for i in range(4)]
frames = []
# Extract frames at the calculated indices
for idx in indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if ret:
# Convert from BGR (OpenCV format) to RGB (Gradio format)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame)
else:
# If frame extraction fails, append None
frames.append(None)
# Release the video capture object
cap.release()
# Return the four frames as a tuple for Gradio outputs
return tuple(frames)
# Create the Gradio interface
iface = gr.Interface(
fn=extract_frames,
inputs=gr.Video(label="Upload a video"),
outputs=[gr.Image(label=f"Frame at {i*25}%") for i in range(4)],
title="Video Frame Extractor",
description="Upload a video to extract four frames from different parts of the video."
)
# Launch the web app
iface.launch()