Certainly! Here's an example of how you can create a Gradio interface that allows you to write text on every frame of a video using OpenCV in Python:
import gradio as gr
import cv2
def write_text_on_video(video_path, text, position, font_size, color):
cap = cv2.VideoCapture(video_path)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))
font = cv2.FONT_HERSHEY_SIMPLEX
color = tuple(map(int, color.split(',')))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cv2.putText(frame, text, position, font, font_size, color, 2, cv2.LINE_AA)
out.write(frame)
cap.release()
out.release()
return 'output.mp4'
inputs = [
gr.inputs.Video(label="Video"),
gr.inputs.Textbox(label="Text"),
gr.inputs.Textbox(label="Position (x,y)", default="50,50"),
gr.inputs.Slider(minimum=0.5, maximum=3, step=0.1, default=1, label="Font Size"),
gr.inputs.Textbox(label="Color (R,G,B)", default="255,255,255")
]
output = gr.outputs.Video(label="Output Video")
title = "Write Text on Video"
description = "Upload a video and provide the text, position, font size, and color to write on every frame of the video."
gr.Interface(fn=write_text_on_video, inputs=inputs, outputs=output, title=title, description=description).launch()
In this example, we define a function called write_text_on_video that takes the following parameters:
video_path: The path to the input video file.
text: The text to be written on each frame of the video.
position: The position (x, y) where the text should be placed on each frame.
font_size: The size of the font for the text.
color: The color of the text in RGB format.
Inside the function, we use OpenCV to read the input video frame by frame. For each frame, we use cv2.putText() to write the specified text at the given position with the provided font size and color. We then write the modified frame to the output video using cv2.VideoWriter().
The Gradio interface is created using gr.Interface(). We define the input components using gr.inputs:
gr.inputs.Video() for uploading the input video.
gr.inputs.Textbox() for entering the text to be written on the video.
gr.inputs.Textbox() for specifying the position of the text.
gr.inputs.Slider() for adjusting the font size.
gr.inputs.Textbox() for specifying the color of the text in RGB format.
The output component is defined using gr.outputs.Video() to display the processed video.
Finally, we provide a title and description for the Gradio interface and launch it using launch().
When you run this code, it will open a web interface where you can upload a video, enter the text, position, font size, and color, and the processed video with the text written on each frame will be displayed as the output.