Spaces:
Running
Running
File size: 2,376 Bytes
368b811 fe4125e 368b811 fe4125e 368b811 |
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 69 |
import gradio as gr
from rembg import remove
from PIL import Image
import numpy as np
import cv2
import os
# Функция для удаления фона с изображения
def remove_bg_from_image(image):
output = remove(image)
return output
# Функция для удаления фона с видео
def remove_bg_from_video(video_path):
# Открываем видео
cap = cv2.VideoCapture(video_path)
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))
# Создаем временный файл для сохранения результата
output_path = "output_video.mp4"
out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height), isColor=True)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Преобразуем кадр в изображение PIL
frame_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
# Удаляем фон
frame_no_bg = remove(frame_pil)
# Преобразуем обратно в массив numpy
frame_no_bg_np = np.array(frame_no_bg)
# Записываем кадр в выходное видео
out.write(cv2.cvtColor(frame_no_bg_np, cv2.COLOR_RGB2BGR))
cap.release()
out.release()
return output_path
# Интерфейс Gradio
def process_input(input_type, input_data):
if input_type == "Image":
output = remove_bg_from_image(input_data)
return output
elif input_type == "Video":
output = remove_bg_from_video(input_data)
return output
# Создаем интерфейс Gradio
input_type = gr.Radio(["Image", "Video"], label="Input Type")
input_data = gr.File(label="Input File") # Используем gr.File вместо gr.inputs.File
interface = gr.Interface(
fn=process_input,
inputs=[input_type, input_data],
outputs=gr.File(label="Output File"), # Используем gr.File вместо gr.outputs.File
title="Background Removal",
description="Remove background from images or videos using rembg."
)
# Запускаем интерфейс
interface.launch() |