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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from network import U2NET
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import cv2
|
| 6 |
+
import gdown
|
| 7 |
+
import argparse
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import torchvision.transforms as transforms
|
| 13 |
+
|
| 14 |
+
from collections import OrderedDict
|
| 15 |
+
from options import opt
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_checkpoint(model, checkpoint_path):
|
| 19 |
+
if not os.path.exists(checkpoint_path):
|
| 20 |
+
print("----No checkpoints at given path----")
|
| 21 |
+
return
|
| 22 |
+
model_state_dict = torch.load(checkpoint_path, map_location=torch.device("cpu"))
|
| 23 |
+
new_state_dict = OrderedDict()
|
| 24 |
+
for k, v in model_state_dict.items():
|
| 25 |
+
name = k[7:] # remove `module.`
|
| 26 |
+
new_state_dict[name] = v
|
| 27 |
+
|
| 28 |
+
model.load_state_dict(new_state_dict)
|
| 29 |
+
print("----checkpoints loaded from path: {}----".format(checkpoint_path))
|
| 30 |
+
return model
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_palette(num_cls):
|
| 34 |
+
""" Returns the color map for visualizing the segmentation mask.
|
| 35 |
+
Args:
|
| 36 |
+
num_cls: Number of classes
|
| 37 |
+
Returns:
|
| 38 |
+
The color map
|
| 39 |
+
"""
|
| 40 |
+
n = num_cls
|
| 41 |
+
palette = [0] * (n * 3)
|
| 42 |
+
for j in range(0, n):
|
| 43 |
+
lab = j
|
| 44 |
+
palette[j * 3 + 0] = 0
|
| 45 |
+
palette[j * 3 + 1] = 0
|
| 46 |
+
palette[j * 3 + 2] = 0
|
| 47 |
+
i = 0
|
| 48 |
+
while lab:
|
| 49 |
+
palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
|
| 50 |
+
palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))
|
| 51 |
+
palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))
|
| 52 |
+
i += 1
|
| 53 |
+
lab >>= 3
|
| 54 |
+
return palette
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class Normalize_image(object):
|
| 58 |
+
"""Normalize given tensor into given mean and standard dev
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
mean (float): Desired mean to substract from tensors
|
| 62 |
+
std (float): Desired std to divide from tensors
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, mean, std):
|
| 66 |
+
assert isinstance(mean, (float))
|
| 67 |
+
if isinstance(mean, float):
|
| 68 |
+
self.mean = mean
|
| 69 |
+
|
| 70 |
+
if isinstance(std, float):
|
| 71 |
+
self.std = std
|
| 72 |
+
|
| 73 |
+
self.normalize_1 = transforms.Normalize(self.mean, self.std)
|
| 74 |
+
self.normalize_3 = transforms.Normalize([self.mean] * 3, [self.std] * 3)
|
| 75 |
+
self.normalize_18 = transforms.Normalize([self.mean] * 18, [self.std] * 18)
|
| 76 |
+
|
| 77 |
+
def __call__(self, image_tensor):
|
| 78 |
+
if image_tensor.shape[0] == 1:
|
| 79 |
+
return self.normalize_1(image_tensor)
|
| 80 |
+
|
| 81 |
+
elif image_tensor.shape[0] == 3:
|
| 82 |
+
return self.normalize_3(image_tensor)
|
| 83 |
+
|
| 84 |
+
elif image_tensor.shape[0] == 18:
|
| 85 |
+
return self.normalize_18(image_tensor)
|
| 86 |
+
|
| 87 |
+
else:
|
| 88 |
+
assert "Please set proper channels! Normlization implemented only for 1, 3 and 18"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def apply_transform(img):
|
| 94 |
+
transforms_list = []
|
| 95 |
+
transforms_list += [transforms.ToTensor()]
|
| 96 |
+
transforms_list += [Normalize_image(0.5, 0.5)]
|
| 97 |
+
transform_rgb = transforms.Compose(transforms_list)
|
| 98 |
+
return transform_rgb(img)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def generate_mask(input_image, net, palette, device = 'cpu'):
|
| 103 |
+
|
| 104 |
+
#img = Image.open(input_image).convert('RGB')
|
| 105 |
+
img = input_image
|
| 106 |
+
img_size = img.size
|
| 107 |
+
img = img.resize((768, 768), Image.BICUBIC)
|
| 108 |
+
image_tensor = apply_transform(img)
|
| 109 |
+
image_tensor = torch.unsqueeze(image_tensor, 0)
|
| 110 |
+
|
| 111 |
+
alpha_out_dir = os.path.join(opt.output,'alpha')
|
| 112 |
+
cloth_seg_out_dir = os.path.join(opt.output,'cloth_seg')
|
| 113 |
+
|
| 114 |
+
os.makedirs(alpha_out_dir, exist_ok=True)
|
| 115 |
+
os.makedirs(cloth_seg_out_dir, exist_ok=True)
|
| 116 |
+
|
| 117 |
+
with torch.no_grad():
|
| 118 |
+
output_tensor = net(image_tensor.to(device))
|
| 119 |
+
output_tensor = F.log_softmax(output_tensor[0], dim=1)
|
| 120 |
+
output_tensor = torch.max(output_tensor, dim=1, keepdim=True)[1]
|
| 121 |
+
output_tensor = torch.squeeze(output_tensor, dim=0)
|
| 122 |
+
output_arr = output_tensor.cpu().numpy()
|
| 123 |
+
|
| 124 |
+
classes_to_save = []
|
| 125 |
+
|
| 126 |
+
# Check which classes are present in the image
|
| 127 |
+
for cls in range(1, 4): # Exclude background class (0)
|
| 128 |
+
if np.any(output_arr == cls):
|
| 129 |
+
classes_to_save.append(cls)
|
| 130 |
+
|
| 131 |
+
# Save alpha masks
|
| 132 |
+
for cls in classes_to_save:
|
| 133 |
+
alpha_mask = (output_arr == cls).astype(np.uint8) * 255
|
| 134 |
+
alpha_mask = alpha_mask[0] # Selecting the first channel to make it 2D
|
| 135 |
+
alpha_mask_img = Image.fromarray(alpha_mask, mode='L')
|
| 136 |
+
alpha_mask_img = alpha_mask_img.resize(img_size, Image.BICUBIC)
|
| 137 |
+
alpha_mask_img.save(os.path.join(alpha_out_dir, f'{cls}.png'))
|
| 138 |
+
|
| 139 |
+
# Save final cloth segmentations
|
| 140 |
+
cloth_seg = Image.fromarray(output_arr[0].astype(np.uint8), mode='P')
|
| 141 |
+
cloth_seg.putpalette(palette)
|
| 142 |
+
cloth_seg = cloth_seg.resize(img_size, Image.BICUBIC)
|
| 143 |
+
cloth_seg.save(os.path.join(cloth_seg_out_dir, 'final_seg.png'))
|
| 144 |
+
return cloth_seg
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def check_or_download_model(file_path):
|
| 149 |
+
if not os.path.exists(file_path):
|
| 150 |
+
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
| 151 |
+
url = "https://drive.google.com/uc?id=11xTBALOeUkyuaK3l60CpkYHLTmv7k3dY"
|
| 152 |
+
gdown.download(url, file_path, quiet=False)
|
| 153 |
+
print("Model downloaded successfully.")
|
| 154 |
+
else:
|
| 155 |
+
print("Model already exists.")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_seg_model(checkpoint_path, device='cpu'):
|
| 159 |
+
net = U2NET(in_ch=3, out_ch=4)
|
| 160 |
+
check_or_download_model(checkpoint_path)
|
| 161 |
+
net = load_checkpoint(net, checkpoint_path)
|
| 162 |
+
net = net.to(device)
|
| 163 |
+
net = net.eval()
|
| 164 |
+
|
| 165 |
+
return net
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def main(args):
|
| 169 |
+
|
| 170 |
+
device = 'cuda:0' if args.cuda else 'cpu'
|
| 171 |
+
|
| 172 |
+
# Create an instance of your model
|
| 173 |
+
model = load_seg_model(args.checkpoint_path, device=device)
|
| 174 |
+
|
| 175 |
+
palette = get_palette(4)
|
| 176 |
+
|
| 177 |
+
img = Image.open(args.image).convert('RGB')
|
| 178 |
+
|
| 179 |
+
cloth_seg = generate_mask(img, net=model, palette=palette, device=device)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == '__main__':
|
| 184 |
+
parser = argparse.ArgumentParser(description='Help to set arguments for Cloth Segmentation.')
|
| 185 |
+
parser.add_argument('--image', type=str, help='Path to the input image')
|
| 186 |
+
parser.add_argument('--cuda', action='store_true', help='Enable CUDA (default: False)')
|
| 187 |
+
parser.add_argument('--checkpoint_path', type=str, default='model/cloth_segm.pth', help='Path to the checkpoint file')
|
| 188 |
+
args = parser.parse_args()
|
| 189 |
+
|
| 190 |
+
main(args)
|