3v324v23 commited on
Commit
6fc8840
1 Parent(s): b6989df

Add application file

Browse files
Files changed (1) hide show
  1. app/app.py +354 -0
app/app.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.append(os.path.abspath(os.path.dirname(os.getcwd())))
4
+ os.chdir("../")
5
+ import cv2
6
+ import gradio as gr
7
+ import numpy as np
8
+ from pathlib import Path
9
+ from matplotlib import pyplot as plt
10
+ import torch
11
+ import tempfile
12
+ # from omegaconf import OmegaConf
13
+ # from sam_segment import predict_masks_with_sam
14
+ from stable_diffusion_inpaint import replace_img_with_sd
15
+ from lama_inpaint import inpaint_img_with_lama, build_lama_model, inpaint_img_with_builded_lama
16
+ from utils import load_img_to_array, save_array_to_img, dilate_mask, \
17
+ show_mask, show_points
18
+ from PIL import Image
19
+ from segment_anything import SamPredictor, sam_model_registry
20
+ import argparse
21
+
22
+ def setup_args(parser):
23
+ parser.add_argument(
24
+ "--lama_config", type=str,
25
+ default="./lama/configs/prediction/default.yaml",
26
+ help="The path to the config file of lama model. "
27
+ "Default: the config of big-lama",
28
+ )
29
+ parser.add_argument(
30
+ "--lama_ckpt", type=str,
31
+ default="pretrained_models/big-lama",
32
+ help="The path to the lama checkpoint.",
33
+ )
34
+ parser.add_argument(
35
+ "--sam_ckpt", type=str,
36
+ default="./pretrained_models/sam_vit_h_4b8939.pth",
37
+ help="The path to the SAM checkpoint to use for mask generation.",
38
+ )
39
+ def mkstemp(suffix, dir=None):
40
+ fd, path = tempfile.mkstemp(suffix=f"{suffix}", dir=dir)
41
+ os.close(fd)
42
+ return Path(path)
43
+
44
+
45
+ def get_sam_feat(img):
46
+ model['sam'].set_image(img)
47
+ features = model['sam'].features
48
+ orig_h = model['sam'].orig_h
49
+ orig_w = model['sam'].orig_w
50
+ input_h = model['sam'].input_h
51
+ input_w = model['sam'].input_w
52
+ model['sam'].reset_image()
53
+ return features, orig_h, orig_w, input_h, input_w
54
+
55
+ def get_replace_img_with_sd(image, mask, image_resolution, text_prompt):
56
+ device = "cuda" if torch.cuda.is_available() else "cpu"
57
+ if len(mask.shape)==3:
58
+ mask = mask[:,:,0]
59
+ np_image = np.array(image, dtype=np.uint8)
60
+ H, W, C = np_image.shape
61
+ np_image = HWC3(np_image)
62
+ np_image = resize_image(np_image, image_resolution)
63
+
64
+ img_replaced = replace_img_with_sd(np_image, mask, text_prompt, device=device)
65
+ img_replaced = img_replaced.astype(np.uint8)
66
+ return img_replaced
67
+
68
+ def HWC3(x):
69
+ assert x.dtype == np.uint8
70
+ if x.ndim == 2:
71
+ x = x[:, :, None]
72
+ assert x.ndim == 3
73
+ H, W, C = x.shape
74
+ assert C == 1 or C == 3 or C == 4
75
+ if C == 3:
76
+ return x
77
+ if C == 1:
78
+ return np.concatenate([x, x, x], axis=2)
79
+ if C == 4:
80
+ color = x[:, :, 0:3].astype(np.float32)
81
+ alpha = x[:, :, 3:4].astype(np.float32) / 255.0
82
+ y = color * alpha + 255.0 * (1.0 - alpha)
83
+ y = y.clip(0, 255).astype(np.uint8)
84
+ return y
85
+
86
+ def resize_image(input_image, resolution):
87
+ H, W, C = input_image.shape
88
+ H = float(H)
89
+ W = float(W)
90
+ k = float(resolution) / min(H, W)
91
+ H *= k
92
+ W *= k
93
+ H = int(np.round(H / 64.0)) * 64
94
+ W = int(np.round(W / 64.0)) * 64
95
+ img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
96
+ return img
97
+
98
+ def resize_points(clicked_points, original_shape, resolution):
99
+ original_height, original_width, _ = original_shape
100
+ original_height = float(original_height)
101
+ original_width = float(original_width)
102
+
103
+ scale_factor = float(resolution) / min(original_height, original_width)
104
+ resized_points = []
105
+
106
+ for point in clicked_points:
107
+ x, y, lab = point
108
+ resized_x = int(round(x * scale_factor))
109
+ resized_y = int(round(y * scale_factor))
110
+ resized_point = (resized_x, resized_y, lab)
111
+ resized_points.append(resized_point)
112
+
113
+ return resized_points
114
+
115
+ def get_click_mask(clicked_points, features, orig_h, orig_w, input_h, input_w):
116
+ # model['sam'].set_image(image)
117
+ model['sam'].is_image_set = True
118
+ model['sam'].features = features
119
+ model['sam'].orig_h = orig_h
120
+ model['sam'].orig_w = orig_w
121
+ model['sam'].input_h = input_h
122
+ model['sam'].input_w = input_w
123
+
124
+ # Separate the points and labels
125
+ points, labels = zip(*[(point[:2], point[2])
126
+ for point in clicked_points])
127
+
128
+ # Convert the points and labels to numpy arrays
129
+ input_point = np.array(points)
130
+ input_label = np.array(labels)
131
+
132
+ masks, _, _ = model['sam'].predict(
133
+ point_coords=input_point,
134
+ point_labels=input_label,
135
+ multimask_output=False,
136
+ )
137
+ if dilate_kernel_size is not None:
138
+ masks = [dilate_mask(mask, dilate_kernel_size.value) for mask in masks]
139
+ else:
140
+ masks = [mask for mask in masks]
141
+
142
+ return masks
143
+
144
+ def process_image_click(original_image, point_prompt, clicked_points, image_resolution, features, orig_h, orig_w, input_h, input_w, evt: gr.SelectData):
145
+ clicked_coords = evt.index
146
+ x, y = clicked_coords
147
+ label = point_prompt
148
+ lab = 1 if label == "Foreground Point" else 0
149
+ clicked_points.append((x, y, lab))
150
+
151
+ input_image = np.array(original_image, dtype=np.uint8)
152
+ H, W, C = input_image.shape
153
+ input_image = HWC3(input_image)
154
+ img = resize_image(input_image, image_resolution)
155
+
156
+ # Update the clicked_points
157
+ resized_points = resize_points(
158
+ clicked_points, input_image.shape, image_resolution
159
+ )
160
+ mask_click_np = get_click_mask(resized_points, features, orig_h, orig_w, input_h, input_w)
161
+
162
+ # Convert mask_click_np to HWC format
163
+ mask_click_np = np.transpose(mask_click_np, (1, 2, 0)) * 255.0
164
+
165
+ mask_image = HWC3(mask_click_np.astype(np.uint8))
166
+ mask_image = cv2.resize(
167
+ mask_image, (W, H), interpolation=cv2.INTER_LINEAR)
168
+ # mask_image = Image.fromarray(mask_image_tmp)
169
+
170
+ # Draw circles for all clicked points
171
+ edited_image = input_image
172
+ for x, y, lab in clicked_points:
173
+ # Set the circle color based on the label
174
+ color = (255, 0, 0) if lab == 1 else (0, 0, 255)
175
+
176
+ # Draw the circle
177
+ edited_image = cv2.circle(edited_image, (x, y), 20, color, -1)
178
+
179
+ # Set the opacity for the mask_image and edited_image
180
+ opacity_mask = 0.75
181
+ opacity_edited = 1.0
182
+
183
+ # Combine the edited_image and the mask_image using cv2.addWeighted()
184
+ overlay_image = cv2.addWeighted(
185
+ edited_image,
186
+ opacity_edited,
187
+ (mask_image *
188
+ np.array([0 / 255, 255 / 255, 0 / 255])).astype(np.uint8),
189
+ opacity_mask,
190
+ 0,
191
+ )
192
+
193
+ return (
194
+ overlay_image,
195
+ # Image.fromarray(overlay_image),
196
+ clicked_points,
197
+ # Image.fromarray(mask_image),
198
+ mask_image
199
+ )
200
+
201
+ def image_upload(image, image_resolution):
202
+ if image is not None:
203
+ np_image = np.array(image, dtype=np.uint8)
204
+ H, W, C = np_image.shape
205
+ np_image = HWC3(np_image)
206
+ np_image = resize_image(np_image, image_resolution)
207
+ features, orig_h, orig_w, input_h, input_w = get_sam_feat(np_image)
208
+ return image, features, orig_h, orig_w, input_h, input_w
209
+ else:
210
+ return None, None, None, None, None, None
211
+
212
+ def get_inpainted_img(image, mask, image_resolution):
213
+ lama_config = args.lama_config
214
+ device = "cuda" if torch.cuda.is_available() else "cpu"
215
+ if len(mask.shape)==3:
216
+ mask = mask[:,:,0]
217
+ img_inpainted = inpaint_img_with_builded_lama(
218
+ model['lama'], image, mask, lama_config, device=device)
219
+ return img_inpainted
220
+
221
+
222
+ # get args
223
+ parser = argparse.ArgumentParser()
224
+ setup_args(parser)
225
+ args = parser.parse_args(sys.argv[1:])
226
+ # build models
227
+ model = {}
228
+ # build the sam model
229
+ model_type="vit_h"
230
+ ckpt_p=args.sam_ckpt
231
+ model_sam = sam_model_registry[model_type](checkpoint=ckpt_p)
232
+ device = "cuda" if torch.cuda.is_available() else "cpu"
233
+ model_sam.to(device=device)
234
+ model['sam'] = SamPredictor(model_sam)
235
+
236
+ # build the lama model
237
+ lama_config = args.lama_config
238
+ lama_ckpt = args.lama_ckpt
239
+ device = "cuda" if torch.cuda.is_available() else "cpu"
240
+ model['lama'] = build_lama_model(lama_config, lama_ckpt, device=device)
241
+
242
+ button_size = (100,50)
243
+ with gr.Blocks() as demo:
244
+ clicked_points = gr.State([])
245
+ origin_image = gr.State(None)
246
+ click_mask = gr.State(None)
247
+ features = gr.State(None)
248
+ orig_h = gr.State(None)
249
+ orig_w = gr.State(None)
250
+ input_h = gr.State(None)
251
+ input_w = gr.State(None)
252
+
253
+ with gr.Row():
254
+ with gr.Column(variant="panel"):
255
+ with gr.Row():
256
+ gr.Markdown("## Input Image")
257
+ with gr.Row():
258
+ # img = gr.Image(label="Input Image")
259
+ source_image_click = gr.Image(
260
+ type="numpy",
261
+ height=300,
262
+ interactive=True,
263
+ label="Image: Upload an image and click the region you want to edit.",
264
+ )
265
+ with gr.Row():
266
+ point_prompt = gr.Radio(
267
+ choices=["Foreground Point",
268
+ "Background Point"],
269
+ value="Foreground Point",
270
+ label="Point Label",
271
+ interactive=True,
272
+ show_label=False,
273
+ )
274
+ image_resolution = gr.Slider(
275
+ label="Image Resolution",
276
+ minimum=256,
277
+ maximum=768,
278
+ value=512,
279
+ step=64,
280
+ )
281
+ dilate_kernel_size = gr.Slider(label="Dilate Kernel Size", minimum=0, maximum=30, step=1, value=3)
282
+ with gr.Column(variant="panel"):
283
+ with gr.Row():
284
+ gr.Markdown("## Control Panel")
285
+ text_prompt = gr.Textbox(label="Text Prompt")
286
+ lama = gr.Button("Inpaint Image", variant="primary")
287
+ replace_sd = gr.Button("Replace Anything with SD", variant="primary")
288
+ clear_button_image = gr.Button(value="Reset", label="Reset", variant="secondary")
289
+
290
+ # todo: maybe we can delete this row, for it's unnecessary to show the original mask for customers
291
+ with gr.Row(variant="panel"):
292
+ with gr.Column():
293
+ with gr.Row():
294
+ gr.Markdown("## Mask")
295
+ with gr.Row():
296
+ click_mask = gr.Image(type="numpy", label="Click Mask")
297
+ with gr.Column():
298
+ with gr.Row():
299
+ gr.Markdown("## Image Removed with Mask")
300
+ with gr.Row():
301
+ img_rm_with_mask = gr.Image(
302
+ type="numpy", label="Image Removed with Mask")
303
+ with gr.Column():
304
+ with gr.Row():
305
+ gr.Markdown("## Replace Anything with Mask")
306
+ with gr.Row():
307
+ img_replace_with_mask = gr.Image(
308
+ type="numpy", label="Image Replace Anything with Mask")
309
+
310
+ source_image_click.upload(
311
+ image_upload,
312
+ inputs=[source_image_click, image_resolution],
313
+ outputs=[origin_image, features, orig_h, orig_w, input_h, input_w],
314
+ )
315
+ source_image_click.select(
316
+ process_image_click,
317
+ inputs=[origin_image, point_prompt,
318
+ clicked_points, image_resolution,
319
+ features, orig_h, orig_w, input_h, input_w],
320
+ outputs=[source_image_click, clicked_points, click_mask],
321
+ show_progress=True,
322
+ queue=True,
323
+ )
324
+
325
+ # sam_mask.click(
326
+ # get_masked_img,
327
+ # [origin_image, w, h, features, orig_h, orig_w, input_h, input_w, dilate_kernel_size],
328
+ # [img_with_mask_0, img_with_mask_1, img_with_mask_2, mask_0, mask_1, mask_2]
329
+ # )
330
+
331
+ lama.click(
332
+ get_inpainted_img,
333
+ [origin_image, click_mask, image_resolution],
334
+ [img_rm_with_mask]
335
+ )
336
+
337
+ replace_sd.click(
338
+ get_replace_img_with_sd,
339
+ [origin_image, click_mask, image_resolution, text_prompt],
340
+ [img_replace_with_mask]
341
+ )
342
+
343
+
344
+ def reset(*args):
345
+ return [None for _ in args]
346
+
347
+ clear_button_image.click(
348
+ reset,
349
+ [origin_image, features, click_mask, img_rm_with_mask, img_replace_with_mask],
350
+ [origin_image, features, click_mask, img_rm_with_mask, img_replace_with_mask]
351
+ )
352
+
353
+ if __name__ == "__main__":
354
+ demo.queue(api_open=False).launch(server_name='0.0.0.0', share=False, debug=True)