geniusq1981 szk1ck commited on
Commit
cdf6850
·
0 Parent(s):

Duplicate from szk1ck/image-matting

Browse files

Co-authored-by: Akihiro SUZUKI <szk1ck@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Image Matting
3
+ emoji: 🐢
4
+ colorFrom: green
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.20.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ duplicated_from: szk1ck/image-matting
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from zipfile import ZipFile
2
+ import numpy as np
3
+
4
+ import os, shutil
5
+
6
+ import gradio as gr
7
+ from PIL import Image
8
+ import sys, os
9
+ from rembg import remove
10
+ from utils import functions
11
+ from utils.functions import complete, clean, clean_by_name, get_random_name
12
+
13
+ import os, sys
14
+ import argparse
15
+
16
+ from logging import getLogger, StreamHandler, DEBUG
17
+ logger = getLogger(__name__)
18
+ handler = StreamHandler(); handler.setLevel(DEBUG)
19
+ logger.setLevel(DEBUG)
20
+ logger.addHandler(handler)
21
+ logger.propagate = False
22
+
23
+
24
+
25
+ def run_rembg(img):
26
+ output = remove(img)
27
+ output_pil = Image.fromarray(output)
28
+
29
+ # Remove margins
30
+ cropped_image = output_pil.crop(output_pil.getbbox())
31
+
32
+ return cropped_image
33
+
34
+
35
+ def from_zip(inputs):
36
+ work_dir = get_random_name()
37
+ os.makedirs(work_dir, exist_ok=True)
38
+
39
+ image_data_dict = {}
40
+ with ZipFile(inputs[0].name, "r") as zip_file:
41
+ image_names = zip_file.namelist()
42
+
43
+ prefix = ""
44
+ for name in image_names:
45
+ if prefix=="":
46
+ prefix = name.split("/")[0]
47
+ else:
48
+ break
49
+
50
+ image_files = []
51
+
52
+ for image_name in image_names:
53
+ if image_name[-3:] in "pngjpg":
54
+ try:
55
+ with zip_file.open(image_name) as f:
56
+ image = Image.open(f)
57
+ image_files.append(image_name)
58
+
59
+ image_array = np.array(image)
60
+ # logger.debug(f"image name : {image_name}")
61
+ category_dir = image_name.split("/")[0]
62
+ # image_name = image_name.split("/")[1]
63
+ os.makedirs(f"{work_dir}/{category_dir}", exist_ok=True)
64
+ image_data_dict[image_name] = image_array
65
+
66
+ except Exception as e:
67
+ logger.info(f"Exception : {e}")
68
+
69
+
70
+ for image_name, image_data in image_data_dict.items():
71
+
72
+ output = remove(image_data)
73
+ output_pil = Image.fromarray(output)
74
+ # Remove margins
75
+ cropped_image = output_pil.crop(output_pil.getbbox())
76
+
77
+ image_name = image_name.replace("jpg", "png")
78
+ cropped_image.save(f"{work_dir}/{image_name}")
79
+
80
+ shutil.make_archive(work_dir, "zip", work_dir)
81
+ shutil.rmtree(work_dir)
82
+
83
+ return f"{work_dir}.zip", complete(work_dir)
84
+
85
+
86
+ def from_image_files(images, text_class_name):
87
+
88
+ if not text_class_name=="":
89
+ dir_name = text_class_name
90
+ else:
91
+ dir_name = functions.get_random_name()
92
+
93
+ os.makedirs(dir_name, exist_ok=True)
94
+
95
+ for image in images:
96
+ image_name = image.name
97
+ # logger.debug(f"image name : {image_name}")
98
+
99
+ # 読み込み
100
+ image_data = np.array(Image.open(image_name))
101
+
102
+ output = remove(image_data)
103
+ output_pil = Image.fromarray(output)
104
+ # Remove margins
105
+ cropped_image = output_pil.crop(output_pil.getbbox())
106
+
107
+ image_name = image_name.split("/")[-1]
108
+ image_name = image_name[:image_name.find("_", image_name.find("_") + 1)] + ".png"
109
+ # logger.debug(f"save image name : {image_name}")
110
+ cropped_image.save(f"{dir_name}/{image_name}")
111
+
112
+ shutil.make_archive(f"{dir_name}", "zip", f"{dir_name}")
113
+ shutil.rmtree(f"{dir_name}")
114
+
115
+ return f"{dir_name}.zip", complete("complete")+"+"+dir_name
116
+
117
+
118
+
119
+
120
+ if __name__=="__main__":
121
+
122
+
123
+ with gr.Blocks() as demo:
124
+
125
+
126
+ with gr.Tab("Images"):
127
+ gr.Markdown(
128
+ """
129
+ <center><h1>Image Matting using U<sup>2</sup>-Net</h1></center>
130
+ """
131
+ )
132
+ with gr.Row():
133
+ gr.Markdown(
134
+ """
135
+ ### Input Image Files
136
+ <img src='file/assets/input_images.png' width="90%" height="90%">
137
+ """
138
+ )
139
+ gr.Markdown(
140
+ """
141
+ ### Output Zip File
142
+ <img src='file/assets/output_zip.png' width="85%" height="85%">
143
+ """
144
+ )
145
+
146
+ with gr.Row():
147
+ with gr.Column():
148
+ text_class_name = gr.Textbox(label="Class Name", value="", placeholder="cat")
149
+ image_input = gr.File(file_count="multiple")
150
+ image_output = gr.File()
151
+ text_output = gr.Textbox(visible=False)
152
+
153
+ btn = gr.Button("Run!")
154
+
155
+ btn.click(
156
+ fn=from_image_files,
157
+ inputs=[image_input, text_class_name],
158
+ outputs=[image_output, text_output]
159
+ )
160
+ text_output.change(
161
+ fn=clean_by_name,
162
+ inputs=text_output,
163
+ outputs=text_output
164
+
165
+ )
166
+
167
+
168
+ with gr.Tab("Zip"):
169
+ gr.Markdown(
170
+ """
171
+ <center><h1>Image Matting using U<sup>2</sup>-Net</h1></center>
172
+ """
173
+ )
174
+ with gr.Row():
175
+ gr.Markdown(
176
+ """
177
+ ### Input Zip File
178
+ <img src='file/assets/input_zip.png' width="85%" height="85%">
179
+ Zip file can include multiple directories.
180
+ """
181
+ )
182
+ gr.Markdown(
183
+ """
184
+ ### Output Zip File
185
+ <img src='file/assets/output_zip.png' width="85%" height="85%">
186
+ If input has multiple directories, output has the same multiple diretocories.
187
+ """
188
+ )
189
+
190
+ with gr.Row():
191
+ image_input = gr.File(file_count="multiple")
192
+ image_output = gr.File()
193
+ text_output = gr.Textbox(visible=False, value="idle_state")
194
+
195
+ btn = gr.Button("Run!")
196
+
197
+ btn.click(
198
+ fn=from_zip,
199
+ inputs=image_input,
200
+ outputs=[image_output, text_output]
201
+ )
202
+ text_output.change(
203
+ fn=clean,
204
+ inputs=text_output,
205
+ outputs=text_output
206
+
207
+ )
208
+
209
+
210
+ with gr.Tab("Image"):
211
+ gr.Markdown(
212
+ """
213
+ <center><h1>Image Matting using U<sup>2</sup>-Net</h1></center>
214
+ """
215
+ )
216
+ with gr.Row():
217
+ gr.Markdown(
218
+ """
219
+ ### Input Image
220
+ <img src='file/assets/cat-3038243_1280.jpg' width="50%" height="50%">
221
+ """
222
+ )
223
+
224
+ gr.Markdown(
225
+ """
226
+ ### Output Image
227
+ <img src='file/assets/objects/cat-3038243_1280.png' width="20%" height="20%">
228
+ """
229
+ )
230
+ with gr.Row():
231
+ image_input = gr.Image(type="numpy")
232
+ image_output = gr.Image(type="pil")
233
+
234
+ btn = gr.Button("Run!")
235
+
236
+
237
+ btn.click(
238
+ fn=run_rembg,
239
+ inputs=image_input,
240
+ outputs=image_output,
241
+ api_name="imageMatting"
242
+ )
243
+
244
+
245
+
246
+
247
+ gr.Markdown(
248
+ """
249
+ ---
250
+ <b>Acknowledgments</b>
251
+ - Library
252
+ - Library Git hub : [danielgatis/rembg](https://github.com/danielgatis/rembg)
253
+ - Cloned on 2023/3/12
254
+ - Algorithm
255
+ - Library Git hub : [U<sup>2</sup>-Net](https://github.com/xuebinqin/U-2-Net)
256
+ - Image
257
+ - Cat Image from [Pixabay](https://pixabay.com/images/id-3038243/)
258
+ """
259
+ )
260
+
261
+ demo.launch(
262
+ favicon_path="./assets/ハサミのフリーアイコン.png"
263
+ )
assets/cat-3038243_1280.jpg ADDED
assets/input_images.png ADDED
assets/input_zip.png ADDED
assets/objects/cat-3038243_1280.png ADDED
assets/output_zip.png ADDED
assets//343/203/217/343/202/265/343/203/237/343/201/256/343/203/225/343/203/252/343/203/274/343/202/242/343/202/244/343/202/263/343/203/263.png ADDED
requirements.txt ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.1.0
2
+ aiohttp==3.8.4
3
+ aiosignal==1.3.1
4
+ altair==4.2.2
5
+ anyio==3.6.2
6
+ appdirs==1.4.4
7
+ async-timeout==4.0.2
8
+ asyncer==0.0.2
9
+ attrs==22.2.0
10
+ blessed==1.20.0
11
+ certifi==2022.12.7
12
+ charset-normalizer==3.1.0
13
+ click==8.1.3
14
+ codefind==0.1.3
15
+ coloredlogs==15.0.1
16
+ contourpy==1.0.7
17
+ cycler==0.11.0
18
+ entrypoints==0.4
19
+ fastapi==0.87.0
20
+ ffmpy==0.3.0
21
+ filetype==1.2.0
22
+ flatbuffers==23.3.3
23
+ fonttools==4.39.0
24
+ frozenlist==1.3.3
25
+ fsspec==2023.3.0
26
+ gradio==3.20.1
27
+ h11==0.14.0
28
+ httpcore==0.16.3
29
+ httpx==0.23.3
30
+ humanfriendly==10.0
31
+ idna==3.4
32
+ ImageHash==4.3.1
33
+ imageio==2.26.0
34
+ importlib-resources==5.12.0
35
+ Jinja2==3.1.2
36
+ jsonschema==4.17.3
37
+ jurigged==0.5.5
38
+ kiwisolver==1.4.4
39
+ lazy_loader==0.1
40
+ linkify-it-py==2.0.0
41
+ llvmlite==0.39.1
42
+ markdown-it-py==2.2.0
43
+ MarkupSafe==2.1.2
44
+ matplotlib==3.7.1
45
+ mdit-py-plugins==0.3.3
46
+ mdurl==0.1.2
47
+ mpmath==1.3.0
48
+ multidict==6.0.4
49
+ networkx==3.0
50
+ numba==0.56.4
51
+ numpy==1.23.5
52
+ onnxruntime==1.13.1
53
+ opencv-python-headless==4.6.0.66
54
+ orjson==3.8.7
55
+ ovld==0.3.2
56
+ packaging==23.0
57
+ pandas==1.5.3
58
+ Pillow==9.3.0
59
+ pooch==1.6.0
60
+ protobuf==4.22.1
61
+ pycryptodome==3.17
62
+ pydantic==1.10.6
63
+ pydub==0.25.1
64
+ PyMatting==1.1.8
65
+ pyparsing==3.0.9
66
+ pyrsistent==0.19.3
67
+ python-dateutil==2.8.2
68
+ python-multipart==0.0.6
69
+ pytz==2022.7.1
70
+ PyWavelets==1.4.1
71
+ PyYAML==6.0
72
+ rembg==2.0.30
73
+ requests==2.28.2
74
+ rfc3986==1.5.0
75
+ scikit-image==0.19.3
76
+ scipy==1.9.3
77
+ six==1.16.0
78
+ sniffio==1.3.0
79
+ starlette==0.21.0
80
+ sympy==1.11.1
81
+ tifffile==2023.2.28
82
+ toolz==0.12.0
83
+ torch==1.13.1
84
+ torchvision==0.14.1
85
+ tqdm==4.64.1
86
+ typing_extensions==4.5.0
87
+ uc-micro-py==1.0.1
88
+ urllib3==1.26.15
89
+ uvicorn==0.20.0
90
+ watchdog==2.1.9
91
+ wcwidth==0.2.6
92
+ websockets==10.4
93
+ yarl==1.8.2
94
+ zipp==3.15.0
utils/__pycache__/functions.cpython-39.pyc ADDED
Binary file (678 Bytes). View file
 
utils/functions.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, random
2
+ from logging import getLogger, StreamHandler, DEBUG
3
+ logger = getLogger(__name__)
4
+ handler = StreamHandler(); handler.setLevel(DEBUG)
5
+ logger.setLevel(DEBUG)
6
+ logger.addHandler(handler)
7
+ logger.propagate = False
8
+
9
+
10
+ def get_random_name():
11
+ famous_painters = [
12
+ "Leonardo", "DaVinci",
13
+ "Michelangelo",
14
+ "Pablo", "Picasso",
15
+ "Vincent", "VanGogh",
16
+ "Rembrandt", "VanRijn",
17
+ "Claude", "Monet",
18
+ "Salvador", "Dali",
19
+ "Jackson", "Pollock",
20
+ "Andy", "Warhol",
21
+ "Henri", "Matisse",
22
+ "Georgia", "Keeffe",
23
+ "Edvard", "Munch",
24
+ "Wassily", "Kandinsky",
25
+ "Gustav", "Klimt",
26
+ "Rene", "Magritte",
27
+ "Frida", "Kahlo",
28
+ "Edgar", "Degas",
29
+ "Johannes", "Vermeer",
30
+ "Paul", "Cezanne",
31
+ "Marc", "Chagall",
32
+ ]
33
+
34
+ random_painter = random.choice(famous_painters)
35
+
36
+ # 4桁の乱数を生成
37
+ rand_num = random.randint(1000, 9999)
38
+
39
+ return random_painter+str(rand_num)
40
+
41
+
42
+ def complete(work_dir):
43
+ work_dir = work_dir
44
+ # logger.debug(f"complete :", work_dir)
45
+ return work_dir
46
+
47
+
48
+ def clean(text_output):
49
+ # logger.debug(f"text_output : {text_output}")
50
+
51
+ if text_output!="idle_state":
52
+ logger.info(f"clean up : {text_output}.zip")
53
+ os.remove(f"{text_output}.zip")
54
+ return "idle_state"
55
+ else:
56
+ logger.info(f"reset")
57
+ return "idle_state"
58
+
59
+
60
+
61
+ def clean_by_name(text_output):
62
+ # logger.debug(f"text_output : {text_output}")
63
+ if text_output!="idle_state":
64
+ text_output, dir_name = text_output.split("+")
65
+ logger.info(f"clean up : {dir_name}.zip")
66
+ os.remove(f"{dir_name}.zip")
67
+ return "idle_state"
68
+ else:
69
+ logger.info(f"reset")
70
+ return "idle_state"