Update app.py
Browse files
app.py
CHANGED
@@ -17,9 +17,13 @@ from model.pipeline import CatVTONPipeline, CatVTONPix2PixPipeline
|
|
17 |
from model.flux.pipeline_flux_tryon import FluxTryOnPipeline
|
18 |
from utils import init_weight_dtype, resize_and_crop, resize_and_padding
|
19 |
|
|
|
20 |
|
|
|
21 |
def parse_args():
|
|
|
22 |
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
|
|
23 |
parser.add_argument(
|
24 |
"--base_model_path",
|
25 |
type=str,
|
@@ -28,14 +32,7 @@ def parse_args():
|
|
28 |
"The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
|
29 |
),
|
30 |
)
|
31 |
-
|
32 |
-
"--p2p_base_model_path",
|
33 |
-
type=str,
|
34 |
-
default="timbrooks/instruct-pix2pix",
|
35 |
-
help=(
|
36 |
-
"The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
|
37 |
-
),
|
38 |
-
)
|
39 |
parser.add_argument(
|
40 |
"--resume_path",
|
41 |
type=str,
|
@@ -96,18 +93,24 @@ def parse_args():
|
|
96 |
)
|
97 |
|
98 |
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
99 |
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
100 |
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
101 |
args.local_rank = env_local_rank
|
102 |
|
103 |
return args
|
104 |
|
|
|
105 |
def image_grid(imgs, rows, cols):
|
106 |
-
assert len(imgs) == rows * cols
|
107 |
|
108 |
w, h = imgs[0].size
|
109 |
-
grid = Image.new("RGB", size=(cols * w, rows * h))
|
110 |
|
|
|
111 |
for i, img in enumerate(imgs):
|
112 |
grid.paste(img, box=(i % cols * w, i // cols * h))
|
113 |
return grid
|
@@ -117,57 +120,89 @@ args = parse_args()
|
|
117 |
|
118 |
# Mask-based CatVTON
|
119 |
catvton_repo = "zhengchong/CatVTON"
|
120 |
-
repo_path = snapshot_download(repo_id=catvton_repo)
|
121 |
-
|
|
|
122 |
pipeline = CatVTONPipeline(
|
123 |
-
base_ckpt=args.base_model_path,
|
124 |
-
attn_ckpt=repo_path,
|
125 |
attn_ckpt_version="mix",
|
126 |
-
weight_dtype=init_weight_dtype(args.mixed_precision),
|
127 |
-
use_tf32=args.allow_tf32,
|
128 |
-
device='cuda'
|
129 |
)
|
130 |
-
|
131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
automasker = AutoMasker(
|
133 |
-
densepose_ckpt=os.path.join(repo_path, "DensePose"),
|
134 |
-
schp_ckpt=os.path.join(repo_path, "SCHP"),
|
135 |
device='cuda',
|
136 |
)
|
137 |
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
@spaces.GPU(duration=120)
|
143 |
def submit_function(
|
144 |
person_image,
|
145 |
cloth_image,
|
146 |
-
cloth_type,
|
147 |
num_inference_steps,
|
148 |
guidance_scale,
|
149 |
seed,
|
150 |
-
show_type
|
151 |
):
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
156 |
else:
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
|
161 |
-
|
162 |
-
|
163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
|
165 |
-
os.makedirs(os.path.join(tmp_folder, date_str[:8]))
|
166 |
|
|
|
167 |
generator = None
|
168 |
-
if seed != -1:
|
169 |
generator = torch.Generator(device='cuda').manual_seed(seed)
|
170 |
|
|
|
171 |
person_image = Image.open(person_image).convert("RGB")
|
172 |
cloth_image = Image.open(cloth_image).convert("RGB")
|
173 |
person_image = resize_and_crop(person_image, (args.width, args.height))
|
@@ -175,14 +210,15 @@ def submit_function(
|
|
175 |
|
176 |
# Process mask
|
177 |
if mask is not None:
|
178 |
-
mask = resize_and_crop(mask, (args.width, args.height))
|
179 |
else:
|
180 |
mask = automasker(
|
181 |
person_image,
|
182 |
cloth_type
|
183 |
-
)['mask']
|
184 |
-
mask = mask_processor.blur(mask, blur_factor=9)
|
185 |
|
|
|
186 |
# Inference
|
187 |
# try:
|
188 |
result_image = pipeline(
|
@@ -198,10 +234,13 @@ def submit_function(
|
|
198 |
# "An error occurred. Please try again later: {}".format(e)
|
199 |
# )
|
200 |
|
201 |
-
# Post-process
|
202 |
-
|
203 |
-
|
|
|
204 |
save_result_image.save(result_save_path)
|
|
|
|
|
205 |
if show_type == "result only":
|
206 |
return result_image
|
207 |
else:
|
@@ -212,131 +251,14 @@ def submit_function(
|
|
212 |
else:
|
213 |
condition_width = width // 3
|
214 |
conditions = image_grid([person_image, masked_person , cloth_image], 3, 1)
|
215 |
-
conditions = conditions.resize((condition_width, height), Image.NEAREST)
|
216 |
-
new_result_image = Image.new("RGB", (width + condition_width + 5, height))
|
217 |
-
new_result_image.paste(conditions, (0, 0))
|
218 |
-
new_result_image.paste(result_image, (condition_width + 5, 0))
|
219 |
-
return new_result_image
|
220 |
-
|
221 |
-
@spaces.GPU(duration=120)
|
222 |
-
def submit_function_p2p(
|
223 |
-
person_image,
|
224 |
-
cloth_image,
|
225 |
-
num_inference_steps,
|
226 |
-
guidance_scale,
|
227 |
-
seed):
|
228 |
-
person_image= person_image["background"]
|
229 |
-
|
230 |
-
tmp_folder = args.output_dir
|
231 |
-
date_str = datetime.now().strftime("%Y%m%d%H%M%S")
|
232 |
-
result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
|
233 |
-
if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
|
234 |
-
os.makedirs(os.path.join(tmp_folder, date_str[:8]))
|
235 |
-
|
236 |
-
generator = None
|
237 |
-
if seed != -1:
|
238 |
-
generator = torch.Generator(device='cuda').manual_seed(seed)
|
239 |
-
|
240 |
-
person_image = Image.open(person_image).convert("RGB")
|
241 |
-
cloth_image = Image.open(cloth_image).convert("RGB")
|
242 |
-
person_image = resize_and_crop(person_image, (args.width, args.height))
|
243 |
-
cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
|
244 |
-
|
245 |
-
# Inference
|
246 |
-
try:
|
247 |
-
result_image = pipeline_p2p(
|
248 |
-
image=person_image,
|
249 |
-
condition_image=cloth_image,
|
250 |
-
num_inference_steps=num_inference_steps,
|
251 |
-
guidance_scale=guidance_scale,
|
252 |
-
generator=generator
|
253 |
-
)[0]
|
254 |
-
except Exception as e:
|
255 |
-
raise gr.Error(
|
256 |
-
"An error occurred. Please try again later: {}".format(e)
|
257 |
-
)
|
258 |
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
@spaces.GPU(duration=120)
|
265 |
-
def submit_function_flux(
|
266 |
-
person_image,
|
267 |
-
cloth_image,
|
268 |
-
cloth_type,
|
269 |
-
num_inference_steps,
|
270 |
-
guidance_scale,
|
271 |
-
seed,
|
272 |
-
show_type
|
273 |
-
):
|
274 |
-
|
275 |
-
# Process image editor input
|
276 |
-
person_image, mask = person_image["background"], person_image["layers"][0]
|
277 |
-
mask = Image.open(mask).convert("L")
|
278 |
-
if len(np.unique(np.array(mask))) == 1:
|
279 |
-
mask = None
|
280 |
-
else:
|
281 |
-
mask = np.array(mask)
|
282 |
-
mask[mask > 0] = 255
|
283 |
-
mask = Image.fromarray(mask)
|
284 |
-
|
285 |
-
# Set random seed
|
286 |
-
generator = None
|
287 |
-
if seed != -1:
|
288 |
-
generator = torch.Generator(device='cuda').manual_seed(seed)
|
289 |
-
|
290 |
-
# Process input images
|
291 |
-
person_image = Image.open(person_image).convert("RGB")
|
292 |
-
cloth_image = Image.open(cloth_image).convert("RGB")
|
293 |
-
|
294 |
-
# Adjust image sizes
|
295 |
-
person_image = resize_and_crop(person_image, (args.width, args.height))
|
296 |
-
cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
|
297 |
-
|
298 |
-
# Process mask
|
299 |
-
if mask is not None:
|
300 |
-
mask = resize_and_crop(mask, (args.width, args.height))
|
301 |
-
else:
|
302 |
-
mask = automasker(
|
303 |
-
person_image,
|
304 |
-
cloth_type
|
305 |
-
)['mask']
|
306 |
-
mask = mask_processor.blur(mask, blur_factor=9)
|
307 |
-
|
308 |
-
# Inference
|
309 |
-
result_image = pipeline_flux(
|
310 |
-
image=person_image,
|
311 |
-
condition_image=cloth_image,
|
312 |
-
mask_image=mask,
|
313 |
-
width=args.width,
|
314 |
-
height=args.height,
|
315 |
-
num_inference_steps=num_inference_steps,
|
316 |
-
guidance_scale=guidance_scale,
|
317 |
-
generator=generator
|
318 |
-
).images[0]
|
319 |
-
|
320 |
-
# Post-processing
|
321 |
-
masked_person = vis_mask(person_image, mask)
|
322 |
-
|
323 |
-
# Return result based on show type
|
324 |
-
if show_type == "result only":
|
325 |
-
return result_image
|
326 |
-
else:
|
327 |
-
width, height = person_image.size
|
328 |
-
if show_type == "input & result":
|
329 |
-
condition_width = width // 2
|
330 |
-
conditions = image_grid([person_image, cloth_image], 2, 1)
|
331 |
-
else:
|
332 |
-
condition_width = width // 3
|
333 |
-
conditions = image_grid([person_image, masked_person, cloth_image], 3, 1)
|
334 |
-
|
335 |
-
conditions = conditions.resize((condition_width, height), Image.NEAREST)
|
336 |
-
new_result_image = Image.new("RGB", (width + condition_width + 5, height))
|
337 |
new_result_image.paste(conditions, (0, 0))
|
338 |
new_result_image.paste(result_image, (condition_width + 5, 0))
|
339 |
-
|
340 |
|
341 |
|
342 |
def person_example_fn(image_path):
|
@@ -348,9 +270,10 @@ HEADER = ""
|
|
348 |
def app_gradio():
|
349 |
with gr.Blocks(title="CatVTON") as demo:
|
350 |
gr.Markdown(HEADER)
|
351 |
-
with gr.Tab("Mask-based
|
352 |
with gr.Row():
|
353 |
with gr.Column(scale=1, min_width=350):
|
|
|
354 |
with gr.Row():
|
355 |
image_path = gr.Image(
|
356 |
type="filepath",
|
@@ -361,6 +284,7 @@ def app_gradio():
|
|
361 |
interactive=True, label="Person Image", type="filepath"
|
362 |
)
|
363 |
|
|
|
364 |
with gr.Row():
|
365 |
with gr.Column(scale=1, min_width=230):
|
366 |
cloth_image = gr.Image(
|
@@ -376,12 +300,13 @@ def app_gradio():
|
|
376 |
value="upper",
|
377 |
)
|
378 |
|
379 |
-
|
380 |
submit = gr.Button("Submit")
|
381 |
gr.Markdown(
|
382 |
'<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
|
383 |
)
|
384 |
|
|
|
385 |
gr.Markdown(
|
386 |
'<span style="color: #808080; font-size: small;">Advanced options can adjust details:<br>1. `Inference Step` may enhance details;<br>2. `CFG` is highly correlated with saturation;<br>3. `Random seed` may improve pseudo-shadow.</span>'
|
387 |
)
|
@@ -403,7 +328,9 @@ def app_gradio():
|
|
403 |
value="input & mask & result",
|
404 |
)
|
405 |
|
|
|
406 |
with gr.Column(scale=2, min_width=500):
|
|
|
407 |
result_image = gr.Image(interactive=False, label="Result")
|
408 |
with gr.Row():
|
409 |
# Photo Examples
|
@@ -466,6 +393,7 @@ def app_gradio():
|
|
466 |
person_example_fn, inputs=image_path, outputs=person_image
|
467 |
)
|
468 |
|
|
|
469 |
submit.click(
|
470 |
submit_function,
|
471 |
[
|
@@ -479,10 +407,9 @@ def app_gradio():
|
|
479 |
],
|
480 |
result_image,
|
481 |
)
|
482 |
-
|
483 |
-
|
484 |
|
485 |
demo.queue().launch(share=True, show_error=True)
|
|
|
486 |
|
487 |
|
488 |
if __name__ == "__main__":
|
|
|
17 |
from model.flux.pipeline_flux_tryon import FluxTryOnPipeline
|
18 |
from utils import init_weight_dtype, resize_and_crop, resize_and_padding
|
19 |
|
20 |
+
access_token = os.getenv('HF_ACCESS_TOKEN')
|
21 |
|
22 |
+
# dùng để phân tích các tham số từ dòng lệnh và trả về cấu hình cài đặt cho chương trình
|
23 |
def parse_args():
|
24 |
+
# Khởi tạo đối tượng để quản lý các tham số dòng lệnh.
|
25 |
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
26 |
+
|
27 |
parser.add_argument(
|
28 |
"--base_model_path",
|
29 |
type=str,
|
|
|
32 |
"The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
|
33 |
),
|
34 |
)
|
35 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
parser.add_argument(
|
37 |
"--resume_path",
|
38 |
type=str,
|
|
|
93 |
)
|
94 |
|
95 |
args = parser.parse_args()
|
96 |
+
|
97 |
+
# Xử lý tham số:
|
98 |
+
# Đảm bảo rằng local_rank (chỉ số GPU cục bộ khi chạy phân tán) được đồng bộ từ biến môi trường
|
99 |
+
# Khi chạy các tác vụ huấn luyện phân tán, hệ thống cần biết chỉ số GPU cục bộ để phân bổ tài nguyên.
|
100 |
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
101 |
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
102 |
args.local_rank = env_local_rank
|
103 |
|
104 |
return args
|
105 |
|
106 |
+
# Hàm image_grid tạo một lưới ảnh (grid) từ danh sách các ảnh đầu vào, với số hàng (rows) và số cột (cols) được chỉ định.
|
107 |
def image_grid(imgs, rows, cols):
|
108 |
+
assert len(imgs) == rows * cols # Kiểm tra số lượng ảnh
|
109 |
|
110 |
w, h = imgs[0].size
|
111 |
+
grid = Image.new("RGB", size=(cols * w, rows * h)) # Tạo ảnh trống làm lưới
|
112 |
|
113 |
+
#Duyệt qua các ảnh và ghép vào lưới
|
114 |
for i, img in enumerate(imgs):
|
115 |
grid.paste(img, box=(i % cols * w, i // cols * h))
|
116 |
return grid
|
|
|
120 |
|
121 |
# Mask-based CatVTON
|
122 |
catvton_repo = "zhengchong/CatVTON"
|
123 |
+
repo_path = snapshot_download(repo_id=catvton_repo) # snapshot_download: Hàm này tải toàn bộ dữ liệu mô hình từ kho lưu trữ trên Hugging Face và lưu về máy cục bộ.
|
124 |
+
|
125 |
+
# Pipeline thực hiện Virtual Try on (dùng mask)
|
126 |
pipeline = CatVTONPipeline(
|
127 |
+
base_ckpt=args.base_model_path, # Checkpoint của mô hình cơ sở (dùng để tạo nền tảng cho pipeline).
|
128 |
+
attn_ckpt=repo_path, # Checkpoint chứa các tham số của attention module, được tải từ repo_path.
|
129 |
attn_ckpt_version="mix",
|
130 |
+
weight_dtype=init_weight_dtype(args.mixed_precision), # Kiểu dữ liệu của trọng số mô hình. Được thiết lập bởi hàm init_weight_dtype, có thể là fp16 hoặc bf16 tùy thuộc vào GPU và cấu hình.
|
131 |
+
use_tf32=args.allow_tf32, # Cho phép sử dụng TensorFloat32 trên GPU Ampere (như A100) để tăng tốc.
|
132 |
+
device='cuda' # Thiết bị chạy mô hình (ở đây là cuda, tức GPU).
|
133 |
)
|
134 |
+
|
135 |
+
# AutoMasker Part
|
136 |
+
# VaeImageProcessor: Bộ xử lý hình ảnh được thiết kế để làm việc với các mô hình dựa trên VAE (Variational Autoencoder).
|
137 |
+
mask_processor = VaeImageProcessor(
|
138 |
+
vae_scale_factor=8, # Tỉ lệ nén hình ảnh khi xử lý bằng VAE. Ảnh sẽ được giảm kích thước theo tỉ lệ 1/8.
|
139 |
+
do_normalize=False, # Không thực hiện chuẩn hóa giá trị pixel (ví dụ: chuyển đổi giá trị về khoảng [0, 1]).
|
140 |
+
do_binarize=True, # Chuyển đổi hình ảnh thành nhị phân (chỉ chứa 2 giá trị: 0 hoặc 255). Quan trọng để tạo mặt nạ rõ ràng.
|
141 |
+
do_convert_grayscale=True
|
142 |
+
)
|
143 |
+
# AutoMasker: Công cụ tự động tạo mặt nạ dựa trên các mô hình dự đoán hình dạng cơ thể người và phân đoạn quần áo.
|
144 |
automasker = AutoMasker(
|
145 |
+
densepose_ckpt=os.path.join(repo_path, "DensePose"), # DensePose: Mô hình dự đoán vị trí 3D của cơ thể từ ảnh 2D.
|
146 |
+
schp_ckpt=os.path.join(repo_path, "SCHP"), # SCHP: Mô hình phân đoạn chi tiết cơ thể người (ví dụ: tách tóc, quần áo, da, v.v.).
|
147 |
device='cuda',
|
148 |
)
|
149 |
|
150 |
+
# Hàm này nhận dữ liệu đầu vào (ảnh người, ảnh quần áo, các tham số) và thực hiện các bước xử lý để trả về ảnh kết quả.
|
151 |
+
@spaces.GPU(duration=120) # Gán GPU để thực hiện hàm submit_function, với thời gian tối đa là 120 giây.
|
152 |
+
# Định nghĩa hàm nhận vào các tham số sau
|
|
|
|
|
153 |
def submit_function(
|
154 |
person_image,
|
155 |
cloth_image,
|
156 |
+
cloth_type, # upper, lower, hoặc overall
|
157 |
num_inference_steps,
|
158 |
guidance_scale,
|
159 |
seed,
|
160 |
+
show_type # Kiểu hiển thị kết quả (chỉ kết quả, kết hợp ảnh gốc và kết quả, hoặc hiển thị cả mặt nạ).
|
161 |
):
|
162 |
+
# Xử lý mặt nạ (mask)
|
163 |
+
person_image,
|
164 |
+
mask = person_image["background"], # Lấy ảnh người từ lớp nền.
|
165 |
+
#person_image["layers"][0] # Lấy mặt nạ do người dùng vẽ (nếu có).
|
166 |
+
if len(person_image["layers"]) > 0:
|
167 |
+
# Nếu danh sách không rỗng, lấy phần tử đầu tiên
|
168 |
+
layer = person_image["layers"][0]
|
169 |
+
else:
|
170 |
+
# Nếu danh sách rỗng, thực hiện hành động thay thế hoặc thông báo lỗi
|
171 |
+
layer = None
|
172 |
+
print("Không có layers trong person_image.")
|
173 |
+
print(mask)
|
174 |
+
|
175 |
+
|
176 |
+
#mask = Image.open(mask).convert("L") # Chuyển mặt nạ thành ảnh thang độ xám
|
177 |
+
if mask is None:
|
178 |
+
raise ValueError("Tham số 'mask' bị rỗng.")
|
179 |
+
elif isinstance(mask, (str, bytes)) or hasattr(mask, "read"):
|
180 |
+
mask = Image.open(mask).convert("L")
|
181 |
else:
|
182 |
+
raise ValueError(f"Kiểu dữ liệu '{type(mask)}' của 'mask' không được hỗ trợ.")
|
183 |
+
print("Loại của mask:", type(mask))
|
184 |
+
print("Giá trị của mask:", mask)
|
185 |
|
186 |
+
if len(np.unique(np.array(mask))) == 1: # Nếu mặt nạ chỉ chứa một giá trị (ví dụ: toàn đen hoặc toàn trắng), thì không sử dụng mặt nạ (mask = None).
|
187 |
+
mask = None
|
188 |
+
else:
|
189 |
+
mask = np.array(mask) # Chuyển mặt nạ thành mảng numpy.
|
190 |
+
mask[mask > 0] = 255 # Các pixel có giá trị lớn hơn 0 được chuyển thành 255 (trắng).
|
191 |
+
mask = Image.fromarray(mask) # Chuyển mảng trở lại thành ảnh.
|
192 |
+
|
193 |
+
# Xử lý đường dẫn lưu trữ kết quả
|
194 |
+
tmp_folder = args.output_dir # Thư mục tạm thời lưu kết quả.
|
195 |
+
date_str = datetime.now().strftime("%Y%m%d%H%M%S") # Chuỗi ngày giờ hiện tại (ví dụ: 20250108).
|
196 |
+
result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png") # Đường dẫn đầy đủ để lưu ảnh kết quả.
|
197 |
if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
|
198 |
+
os.makedirs(os.path.join(tmp_folder, date_str[:8])) # Tạo thư mục lưu trữ nếu chưa tồn tại.
|
199 |
|
200 |
+
# Xử lý seed ngẫu nhiên
|
201 |
generator = None
|
202 |
+
if seed != -1: # Nếu seed được cung cấp, mô hình sẽ sử dụng giá trị này để sinh dữ liệu (giữ tính ngẫu nhiên nhưng tái tạo được).
|
203 |
generator = torch.Generator(device='cuda').manual_seed(seed)
|
204 |
|
205 |
+
# Chuẩn hóa ảnh đầu vào
|
206 |
person_image = Image.open(person_image).convert("RGB")
|
207 |
cloth_image = Image.open(cloth_image).convert("RGB")
|
208 |
person_image = resize_and_crop(person_image, (args.width, args.height))
|
|
|
210 |
|
211 |
# Process mask
|
212 |
if mask is not None:
|
213 |
+
mask = resize_and_crop(mask, (args.width, args.height)) # Nếu mặt nạ được cung cấp, thay đổi kích thước cho phù hợp.
|
214 |
else:
|
215 |
mask = automasker(
|
216 |
person_image,
|
217 |
cloth_type
|
218 |
+
)['mask'] # Nếu không, tạo mặt nạ tự động bằng automasker, dựa trên loại quần áo (cloth_type).
|
219 |
+
mask = mask_processor.blur(mask, blur_factor=9) # Làm mờ mặt nạ (blur) để giảm bớt các cạnh sắc
|
220 |
|
221 |
+
# Suy luận mô hình: gán các tham số vô hàm tính toán, trả lại result là hình ảnh
|
222 |
# Inference
|
223 |
# try:
|
224 |
result_image = pipeline(
|
|
|
234 |
# "An error occurred. Please try again later: {}".format(e)
|
235 |
# )
|
236 |
|
237 |
+
# Post-process - Xử lý hậu kỳ
|
238 |
+
# Tạo ảnh kết quả lưới
|
239 |
+
masked_person = vis_mask(person_image, mask) # Hiển thị ảnh người với mặt nạ được áp dụng.
|
240 |
+
save_result_image = image_grid([person_image, masked_person, cloth_image, result_image], 1, 4) # Tạo một ảnh lưới chứa
|
241 |
save_result_image.save(result_save_path)
|
242 |
+
|
243 |
+
# Điều chỉnh hiển thị kết quả
|
244 |
if show_type == "result only":
|
245 |
return result_image
|
246 |
else:
|
|
|
251 |
else:
|
252 |
condition_width = width // 3
|
253 |
conditions = image_grid([person_image, masked_person , cloth_image], 3, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
|
255 |
+
conditions = conditions.resize((condition_width, height), Image.NEAREST)
|
256 |
+
# conditions: Ảnh ghép ban đầu, được tạo từ các ảnh như ảnh người gốc, ảnh quần áo, và ảnh mặt nạ (tùy chọn).
|
257 |
+
# Tham số Image.NEAREST: Đây là phương pháp nội suy (interpolation) gần nhất, dùng để thay đổi kích thước ảnh mà không làm mờ hay mất chi tiết.
|
258 |
+
new_result_image = Image.new("RGB", (width + condition_width + 5, height)) # Image.new: Tạo một ảnh trống mới
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
259 |
new_result_image.paste(conditions, (0, 0))
|
260 |
new_result_image.paste(result_image, (condition_width + 5, 0))
|
261 |
+
return new_result_image
|
262 |
|
263 |
|
264 |
def person_example_fn(image_path):
|
|
|
270 |
def app_gradio():
|
271 |
with gr.Blocks(title="CatVTON") as demo:
|
272 |
gr.Markdown(HEADER)
|
273 |
+
with gr.Tab("Mask-based"):
|
274 |
with gr.Row():
|
275 |
with gr.Column(scale=1, min_width=350):
|
276 |
+
# Ảnh model (người)
|
277 |
with gr.Row():
|
278 |
image_path = gr.Image(
|
279 |
type="filepath",
|
|
|
284 |
interactive=True, label="Person Image", type="filepath"
|
285 |
)
|
286 |
|
287 |
+
# Ảnh quần áo
|
288 |
with gr.Row():
|
289 |
with gr.Column(scale=1, min_width=230):
|
290 |
cloth_image = gr.Image(
|
|
|
300 |
value="upper",
|
301 |
)
|
302 |
|
303 |
+
# Submit button - Run
|
304 |
submit = gr.Button("Submit")
|
305 |
gr.Markdown(
|
306 |
'<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
|
307 |
)
|
308 |
|
309 |
+
# Advance setting
|
310 |
gr.Markdown(
|
311 |
'<span style="color: #808080; font-size: small;">Advanced options can adjust details:<br>1. `Inference Step` may enhance details;<br>2. `CFG` is highly correlated with saturation;<br>3. `Random seed` may improve pseudo-shadow.</span>'
|
312 |
)
|
|
|
328 |
value="input & mask & result",
|
329 |
)
|
330 |
|
331 |
+
|
332 |
with gr.Column(scale=2, min_width=500):
|
333 |
+
# Result image
|
334 |
result_image = gr.Image(interactive=False, label="Result")
|
335 |
with gr.Row():
|
336 |
# Photo Examples
|
|
|
393 |
person_example_fn, inputs=image_path, outputs=person_image
|
394 |
)
|
395 |
|
396 |
+
# Function khi ấn nút submit
|
397 |
submit.click(
|
398 |
submit_function,
|
399 |
[
|
|
|
407 |
],
|
408 |
result_image,
|
409 |
)
|
|
|
|
|
410 |
|
411 |
demo.queue().launch(share=True, show_error=True)
|
412 |
+
#demo.queue().launch()
|
413 |
|
414 |
|
415 |
if __name__ == "__main__":
|