Doubleupai commited on
Commit
368b811
·
verified ·
1 Parent(s): 9df31df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -0
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from rembg import remove
3
+ from PIL import Image
4
+ import numpy as np
5
+ import cv2
6
+ import os
7
+
8
+ # Функция для удаления фона с изображения
9
+ def remove_bg_from_image(image):
10
+ output = remove(image)
11
+ return output
12
+
13
+ # Функция для удаления фона с видео
14
+ def remove_bg_from_video(video_path):
15
+ # Открываем видео
16
+ cap = cv2.VideoCapture(video_path)
17
+ frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
18
+ frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
19
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
20
+
21
+ # Создаем временный файл для сохранения результата
22
+ output_path = "output_video.mp4"
23
+ out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height), isColor=True)
24
+
25
+ while cap.isOpened():
26
+ ret, frame = cap.read()
27
+ if not ret:
28
+ break
29
+
30
+ # Преобразуем кадр в изображение PIL
31
+ frame_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
32
+
33
+ # Удаляем фон
34
+ frame_no_bg = remove(frame_pil)
35
+
36
+ # Преобразуем обратно в массив numpy
37
+ frame_no_bg_np = np.array(frame_no_bg)
38
+
39
+ # Записываем кадр в выходное видео
40
+ out.write(cv2.cvtColor(frame_no_bg_np, cv2.COLOR_RGB2BGR))
41
+
42
+ cap.release()
43
+ out.release()
44
+
45
+ return output_path
46
+
47
+ # Интерфейс Gradio
48
+ def process_input(input_type, input_data):
49
+ if input_type == "Image":
50
+ output = remove_bg_from_image(input_data)
51
+ return output
52
+ elif input_type == "Video":
53
+ output = remove_bg_from_video(input_data)
54
+ return output
55
+
56
+ # Создаем интерфейс Gradio
57
+ input_type = gr.Radio(["Image", "Video"], label="Input Type")
58
+ input_data = gr.inputs.File(label="Input File")
59
+
60
+ interface = gr.Interface(
61
+ fn=process_input,
62
+ inputs=[input_type, input_data],
63
+ outputs=gr.outputs.File(label="Output File"),
64
+ title="Background Removal",
65
+ description="Remove background from images or videos using rembg."
66
+ )
67
+
68
+ # Запускаем интерфейс
69
+ interface.launch()