Navyssh tanuj437 commited on
Commit
f3c020c
·
verified ·
1 Parent(s): 0efe6ed

Upload 3 files (#1)

Browse files

- Upload 3 files (8cd854b130f99a24aa4f0a6e85636940b3a4061a)


Co-authored-by: Tanuj Saxena <tanuj437@users.noreply.huggingface.co>

Files changed (4) hide show
  1. .gitattributes +2 -0
  2. app.py +237 -0
  3. mask_image.jpg +3 -0
  4. output_image.jpg +3 -0
.gitattributes CHANGED
@@ -34,3 +34,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  detectron2/_C.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  detectron2/_C.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
37
+ mask_image.jpg filter=lfs diff=lfs merge=lfs -text
38
+ output_image.jpg filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PIL import Image
3
+ from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
4
+ from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref
5
+ from src.unet_hacked_tryon import UNet2DConditionModel
6
+ from transformers import (
7
+ CLIPImageProcessor,
8
+ CLIPVisionModelWithProjection,
9
+ CLIPTextModel,
10
+ CLIPTextModelWithProjection,
11
+ )
12
+ from diffusers import DDPMScheduler, AutoencoderKL
13
+ import torch
14
+ from transformers import AutoTokenizer
15
+ import numpy as np
16
+ from utils_mask import get_mask_location
17
+ from torchvision import transforms
18
+ import apply_net
19
+ from preprocess.humanparsing.run_parsing import Parsing
20
+ from preprocess.openpose.run_openpose import OpenPose
21
+ from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation
22
+ from torchvision.transforms.functional import to_pil_image
23
+
24
+
25
+ def pil_to_binary_mask(pil_image, threshold=0):
26
+ np_image = np.array(pil_image)
27
+ grayscale_image = Image.fromarray(np_image).convert("L")
28
+ binary_mask = np.array(grayscale_image) > threshold
29
+ mask = np.zeros(binary_mask.shape, dtype=np.uint8)
30
+ for i in range(binary_mask.shape[0]):
31
+ for j in range(binary_mask.shape[1]):
32
+ if binary_mask[i, j]:
33
+ mask[i, j] = 1
34
+ mask = (mask * 255).astype(np.uint8)
35
+ output_mask = Image.fromarray(mask)
36
+ return output_mask
37
+
38
+
39
+ # Load models and configurations
40
+ base_path = 'yisol/IDM-VTON'
41
+ example_path = os.path.join(os.path.dirname(__file__), 'example')
42
+
43
+ unet = UNet2DConditionModel.from_pretrained(
44
+ base_path,
45
+ subfolder="unet",
46
+ torch_dtype=torch.float16,
47
+ )
48
+ unet.requires_grad_(False)
49
+
50
+ tokenizer_one = AutoTokenizer.from_pretrained(
51
+ base_path,
52
+ subfolder="tokenizer",
53
+ revision=None,
54
+ use_fast=False,
55
+ )
56
+ tokenizer_two = AutoTokenizer.from_pretrained(
57
+ base_path,
58
+ subfolder="tokenizer_2",
59
+ revision=None,
60
+ use_fast=False,
61
+ )
62
+ noise_scheduler = DDPMScheduler.from_pretrained(base_path, subfolder="scheduler")
63
+
64
+ text_encoder_one = CLIPTextModel.from_pretrained(
65
+ base_path,
66
+ subfolder="text_encoder",
67
+ torch_dtype=torch.float16,
68
+ )
69
+ text_encoder_two = CLIPTextModelWithProjection.from_pretrained(
70
+ base_path,
71
+ subfolder="text_encoder_2",
72
+ torch_dtype=torch.float16,
73
+ )
74
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
75
+ base_path,
76
+ subfolder="image_encoder",
77
+ torch_dtype=torch.float16,
78
+ )
79
+ vae = AutoencoderKL.from_pretrained(
80
+ base_path,
81
+ subfolder="vae",
82
+ torch_dtype=torch.float16,
83
+ )
84
+
85
+ UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(
86
+ base_path,
87
+ subfolder="unet_encoder",
88
+ torch_dtype=torch.float16,
89
+ )
90
+
91
+ parsing_model = Parsing(0)
92
+ openpose_model = OpenPose(0)
93
+
94
+ UNet_Encoder.requires_grad_(False)
95
+ image_encoder.requires_grad_(False)
96
+ vae.requires_grad_(False)
97
+ unet.requires_grad_(False)
98
+ text_encoder_one.requires_grad_(False)
99
+ text_encoder_two.requires_grad_(False)
100
+
101
+ tensor_transfrom = transforms.Compose(
102
+ [
103
+ transforms.ToTensor(),
104
+ transforms.Normalize([0.5], [0.5]),
105
+ ]
106
+ )
107
+
108
+ pipe = TryonPipeline.from_pretrained(
109
+ base_path,
110
+ unet=unet,
111
+ vae=vae,
112
+ feature_extractor=CLIPImageProcessor(),
113
+ text_encoder=text_encoder_one,
114
+ text_encoder_2=text_encoder_two,
115
+ tokenizer=tokenizer_one,
116
+ tokenizer_2=tokenizer_two,
117
+ scheduler=noise_scheduler,
118
+ image_encoder=image_encoder,
119
+ torch_dtype=torch.float16,
120
+ )
121
+ pipe.unet_encoder = UNet_Encoder
122
+
123
+
124
+ def start_tryon(human_img_path, garm_img_path, garment_des, is_checked=True, is_checked_crop=False, denoise_steps=30, seed=42):
125
+ device = "cuda"
126
+
127
+ openpose_model.preprocessor.body_estimation.model.to(device)
128
+ pipe.to(device)
129
+ pipe.unet_encoder.to(device)
130
+
131
+ garm_img = Image.open(garm_img_path).convert("RGB").resize((768, 1024))
132
+ human_img_orig = Image.open(human_img_path).convert("RGB")
133
+
134
+ if is_checked_crop:
135
+ width, height = human_img_orig.size
136
+ target_width = int(min(width, height * (3 / 4)))
137
+ target_height = int(min(height, width * (4 / 3)))
138
+ left = (width - target_width) / 2
139
+ top = (height - target_height) / 2
140
+ right = (width + target_width) / 2
141
+ bottom = (height + target_height) / 2
142
+ cropped_img = human_img_orig.crop((left, top, right, bottom))
143
+ crop_size = cropped_img.size
144
+ human_img = cropped_img.resize((768, 1024))
145
+ else:
146
+ human_img = human_img_orig.resize((768, 1024))
147
+
148
+ if is_checked:
149
+ keypoints = openpose_model(human_img.resize((384, 512)))
150
+ model_parse, _ = parsing_model(human_img.resize((384, 512)))
151
+ mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints)
152
+ mask = mask.resize((768, 1024))
153
+ else:
154
+ mask = pil_to_binary_mask(human_img.resize((768, 1024)))
155
+
156
+ mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transfrom(human_img)
157
+ mask_gray = to_pil_image((mask_gray + 1.0) / 2.0)
158
+
159
+ human_img_arg = _apply_exif_orientation(human_img.resize((384, 512)))
160
+ human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")
161
+
162
+ args = apply_net.create_argument_parser().parse_args(
163
+ ('show', './configs/densepose_rcnn_R_50_FPN_s1x.yaml', './ckpt/densepose/model_final_162be9.pkl', 'dp_segm', '-v', '--opts', 'MODEL.DEVICE', 'cuda')
164
+ )
165
+ pose_img = args.func(args, human_img_arg)
166
+ pose_img = pose_img[:, :, ::-1]
167
+ pose_img = Image.fromarray(pose_img).resize((768, 1024))
168
+
169
+ with torch.no_grad():
170
+ prompt = "model is wearing " + garment_des
171
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
172
+ (
173
+ prompt_embeds,
174
+ negative_prompt_embeds,
175
+ pooled_prompt_embeds,
176
+ negative_pooled_prompt_embeds,
177
+ ) = pipe.encode_prompt(
178
+ prompt,
179
+ num_images_per_prompt=1,
180
+ do_classifier_free_guidance=True,
181
+ negative_prompt=negative_prompt,
182
+ )
183
+
184
+ prompt = "a photo of " + garment_des
185
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
186
+ (
187
+ prompt_embeds_c,
188
+ _,
189
+ _,
190
+ _,
191
+ ) = pipe.encode_prompt(
192
+ prompt,
193
+ num_images_per_prompt=1,
194
+ do_classifier_free_guidance=False,
195
+ negative_prompt=negative_prompt,
196
+ )
197
+
198
+ pose_img = tensor_transfrom(pose_img).unsqueeze(0).to(device, torch.float16)
199
+ garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device, torch.float16)
200
+ generator = torch.Generator(device).manual_seed(seed) if seed is not None else None
201
+ images = pipe(
202
+ prompt_embeds=prompt_embeds.to(device, torch.float16),
203
+ negative_prompt_embeds=negative_prompt_embeds.to(device, torch.float16),
204
+ pooled_prompt_embeds=pooled_prompt_embeds.to(device, torch.float16),
205
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device, torch.float16),
206
+ num_inference_steps=denoise_steps,
207
+ generator=generator,
208
+ strength=1.0,
209
+ pose_img=pose_img.to(device, torch.float16),
210
+ text_embeds_cloth=prompt_embeds_c.to(device, torch.float16),
211
+ cloth=garm_tensor.to(device, torch.float16),
212
+ mask_image=mask,
213
+ image=human_img,
214
+ height=1024,
215
+ width=768,
216
+ ip_adapter_image=garm_img.resize((768, 1024)),
217
+ guidance_scale=2.0,
218
+ )[0]
219
+
220
+ if is_checked_crop:
221
+ out_img = images[0].resize(crop_size)
222
+ human_img_orig.paste(out_img, (int(left), int(top)))
223
+ return human_img_orig, mask_gray
224
+ else:
225
+ return images[0], mask_gray
226
+
227
+
228
+ # Example usage
229
+ if __name__ == "__main__":
230
+ human_img_path = "WhatsApp Image 2025-02-28 at 21.44.16_e9541a96.jpg"
231
+ garm_img_path = "tshirt.jpg"
232
+ garment_des = "Short Sleeve Round Neck T-shirts"
233
+ output_image, mask_image = start_tryon(human_img_path, garm_img_path, garment_des)
234
+
235
+ # Save the output
236
+ output_image.save("output_image.jpg")
237
+ mask_image.save("mask_image.jpg")
mask_image.jpg ADDED

Git LFS Details

  • SHA256: 1a22c0793ea5c7a2fa0535ac4c8df9bdec8ec0adc2cc38e04f53410be9dea286
  • Pointer size: 131 Bytes
  • Size of remote file: 111 kB
output_image.jpg ADDED

Git LFS Details

  • SHA256: 325308a85cf88ba5840fe2baf4609ac1525758e1bb33eb9ecad7085d37af20f4
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB