Ivanrs commited on
Commit
450f2bc
1 Parent(s): b4af227

Initial commit to HuggingFace

Browse files
Files changed (2) hide show
  1. app.py +59 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rembg import remove
2
+ import gradio as gr
3
+ from PIL import Image
4
+ from zipfile import ZipFile
5
+ import os
6
+
7
+ def crop_and_resize(img, size, proportion):
8
+ frac = proportion
9
+
10
+ left = img.size[0]*((1-frac)/2)
11
+ upper = img.size[1]*((1-frac)/2)
12
+ right = img.size[0]-((1-frac)/2)*img.size[0]
13
+ bottom = img.size[1]-((1-frac)/2)*img.size[1]
14
+
15
+ cropped_img = img.crop((left, upper, right, bottom))
16
+
17
+ newsize = (size, size)
18
+ cropped_img = cropped_img.resize(newsize)
19
+ return cropped_img
20
+
21
+
22
+ def remove_bg(folder, size, proportion):
23
+
24
+ if os.path.exists("images_no_bg.zip"):
25
+ os.remove("images_no_bg.zip")
26
+ else:
27
+ print("The file does not exist")
28
+
29
+ with ZipFile("images_no_bg.zip", "w") as zipObj:
30
+
31
+ for i, file in enumerate(folder):
32
+
33
+ image = Image.open(file)
34
+ image = remove(image)
35
+
36
+ image = crop_and_resize(image, size, proportion)
37
+
38
+ image_name = f"image_{i}.png"
39
+ image.save(image_name)
40
+ zipObj.write(image_name, image_name)
41
+ os.remove(image_name)
42
+
43
+ return "images_no_bg.zip"
44
+
45
+
46
+ interface = gr.Interface(
47
+ title = "Batch Image Background Remover",
48
+ description = "Select a folder with images. Then, select the size of output image (square), and the cropping proportion.",
49
+ allow_flagging="never",
50
+ fn = remove_bg,
51
+ inputs = [
52
+ gr.File(file_count="directory"),
53
+ gr.Slider(400, 800, step = 100, value=600, label = "Size (Square)"),
54
+ gr.Slider(0, 1, value=.7, step = .1, label = "Croping Proportion", precision = None),
55
+ ],
56
+ outputs = "file"
57
+ )
58
+
59
+ interface.launch(share = False)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ rembg
2
+ gradio
3
+ PIL
4
+ zipfile
5
+ os