File size: 15,938 Bytes
64933a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
689a987
 
 
 
 
 
 
64933a5
689a987
 
 
64933a5
689a987
 
 
 
 
 
 
 
 
64933a5
689a987
 
 
 
 
 
 
 
 
 
 
 
64933a5
 
 
 
 
 
 
689a987
 
 
 
64933a5
 
 
 
 
 
 
689a987
 
 
 
64933a5
 
 
 
 
689a987
 
 
 
 
 
 
 
 
 
64933a5
689a987
64933a5
 
689a987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64933a5
 
 
 
 
 
 
 
 
 
 
 
 
 
689a987
 
64933a5
 
 
 
809739f
64933a5
809739f
64933a5
 
 
 
 
 
689a987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64933a5
689a987
64933a5
689a987
 
64933a5
689a987
 
 
 
 
 
 
 
 
 
 
 
64933a5
 
 
 
689a987
 
 
 
 
 
64933a5
689a987
 
 
64933a5
689a987
64933a5
689a987
 
 
 
 
64933a5
 
689a987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64933a5
 
689a987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64933a5
 
 
689a987
64933a5
689a987
 
 
 
 
 
 
 
64933a5
689a987
 
 
 
 
 
64933a5
 
 
 
 
689a987
 
 
 
 
 
 
64933a5
 
 
 
689a987
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# #!/usr/bin/env python
# # -*- encoding: utf-8 -*-

# """
# @Author  :   Peike Li
# @Contact :   peike.li@yahoo.com
# @File    :   simple_extractor.py
# @Time    :   8/30/19 8:59 PM
# @Desc    :   Simple Extractor
# @License :   This source code is licensed under the license found in the
#              LICENSE file in the root directory of this source tree.
# """

# import os
# import torch
# import argparse
# import numpy as np
# from PIL import Image
# from tqdm import tqdm

# from torch.utils.data import DataLoader
# import torchvision.transforms as transforms

# import os
# import sys

# _THIS_DIR = os.path.dirname(os.path.abspath(__file__))  # .../DEMO/preprocess
# if _THIS_DIR not in sys.path:
#     sys.path.insert(0, _THIS_DIR)


# import networks
# from utils.transforms import transform_logits
# from datasets.simple_extractor_dataset import SimpleFolderDataset



# dataset_settings = {
#     'lip': {
#         'input_size': [473, 473],
#         'num_classes': 20,
#         'label': ['Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'Upper-clothes', 'Dress', 'Coat',
#                   'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', 'Face', 'Left-arm', 'Right-arm',
#                   'Left-leg', 'Right-leg', 'Left-shoe', 'Right-shoe']
#     },
#     'atr': {
#         'input_size': [512, 512],
#         'num_classes': 18,
#         'label': ['Background', 'Hat', 'Hair', 'Sunglasses', 'Upper-clothes', 'Skirt', 'Pants', 'Dress', 'Belt',
#                   'Left-shoe', 'Right-shoe', 'Face', 'Left-leg', 'Right-leg', 'Left-arm', 'Right-arm', 'Bag', 'Scarf']
#     },
#     'pascal': {
#         'input_size': [512, 512],
#         'num_classes': 7,
#         'label': ['Background', 'Head', 'Torso', 'Upper Arms', 'Lower Arms', 'Upper Legs', 'Lower Legs'],
#     }
# }


# def get_arguments():
#     """Parse all the arguments provided from the CLI.
#     Returns:
#       A list of parsed arguments.
#     """
#     parser = argparse.ArgumentParser(description="Self Correction for Human Parsing")

#     parser.add_argument("--dataset", type=str, default='atr', choices=['lip', 'atr', 'pascal'])
#     parser.add_argument("--model-restore", type=str, default='', help="restore pretrained model parameters.")
#     parser.add_argument("--gpu", type=str, default='0', help="choose gpu device.")
#     parser.add_argument("--category", type=str, default='Upper-clothes', help="category name (optional).")
#     parser.add_argument("--input-dir", type=str, default='', help="path of input image folder.")
#     parser.add_argument("--output-dir", type=str, default='', help="path of output image folder.")
#     parser.add_argument("--logits", action='store_true', default=False, help="whether to save the logits.")

#     return parser.parse_args()


# def get_palette(num_cls):
#     n = 18
#     palette = [0] * (n * 3)
#     j = num_cls
#     lab = num_cls
#     palette[j * 3 + 0] = 0
#     palette[j * 3 + 1] = 0
#     palette[j * 3 + 2] = 0
#     i = 0
#     while lab:
#         palette[j * 3 + 0] = 255
#         palette[j * 3 + 1] = 255
#         palette[j * 3 + 2] = 255
#         i += 1
#         lab >>= 3
#     return palette

# def get_palette2(num_cls):
#     """ Returns the color map for visualizing the segmentation mask.
#     Args:
#         num_cls: Number of classes
#     Returns:
#         The color map
#     """
#     n = 18
#     palette = [0] * (n * 3)
#     for j in range(5, 7):
#         lab = j
#         palette[j * 3 + 0] = 0
#         palette[j * 3 + 1] = 0
#         palette[j * 3 + 2] = 0
#         i = 0
#         while lab:
#             palette[j * 3 + 0] = 255
#             palette[j * 3 + 1] = 255
#             palette[j * 3 + 2] = 255
#             i += 1
#             lab >>= 3
#     return palette

# def run(
#     *,
#     category: str,
#     input_path: str = "",
#     input_dir: str = "",
#     dataset: str = "atr",
#     model_restore: str = "",
#     gpu: str = "0",
#     logits: bool = False,
# ):
#     """
#     - input_path (๋‹จ์ผ ํŒŒ์ผ) ๋˜๋Š” input_dir(ํด๋”) ์ค‘ ํ•˜๋‚˜๋ฅผ ๋ฐ›์•„ parsing ๊ฒฐ๊ณผ๋ฅผ ๋ฉ”๋ชจ๋ฆฌ๋กœ ๋ฐ˜ํ™˜.
#     - ํŒŒ์ผ ์ €์žฅ ์—†์Œ.

#     Returns:
#         {
#             "images": List[PIL.Image],          # parsing mask (palette ์ ์šฉ๋จ)
#             "logits": Optional[List[np.ndarray]],
#             "names": List[str],                # ํŒŒ์ผ๋ช…๋“ค
#         }
#     """
#     # single GPU๋งŒ ํ—ˆ์šฉ
#     gpus = [int(i) for i in gpu.split(',')]
#     assert len(gpus) == 1
#     if gpu != 'None':
#         os.environ["CUDA_VISIBLE_DEVICES"] = gpu

#     if not model_restore:
#         print("[simple_extractor] model_restore not provided โ†’ skip extractor.")
#         return {"images": [], "logits": [] if logits else None, "names": []}

#     # ์ž…๋ ฅ ๊ฒ€์ฆ: ๋‘˜ ์ค‘ ํ•˜๋‚˜๋Š” ์žˆ์–ด์•ผ ํ•จ
#     if bool(input_path) == bool(input_dir):
#         raise ValueError("Provide exactly one of input_path or input_dir.")

#     # ํŒŒ์ผ์ด๋ฉด ์กด์žฌ ํ™•์ธ
#     if input_path:
#         if not os.path.isfile(input_path):
#             raise FileNotFoundError(f"input_path not found or not a file: {input_path}")

#     # ํด๋”๋ฉด ์กด์žฌ ํ™•์ธ
#     if input_dir:
#         if not os.path.isdir(input_dir):
#             raise NotADirectoryError(f"input_dir not found or not a directory: {input_dir}")

#     num_classes = dataset_settings[dataset]['num_classes']
#     input_size = dataset_settings[dataset]['input_size']
#     label = dataset_settings[dataset]['label']
#     print(f"Evaluating total class number {num_classes} with {label}")

#     model = networks.init_model('resnet101', num_classes=num_classes, pretrained=None)

#     state_dict = torch.load(model_restore)['state_dict']
#     from collections import OrderedDict
#     new_state_dict = OrderedDict()
#     for k, v in state_dict.items():
#         name = k[7:]  # remove `module.`
#         new_state_dict[name] = v

#     model.load_state_dict(new_state_dict)
#     model.cuda()
#     model.eval()

#     transform = transforms.Compose([
#         transforms.ToTensor(),
#         transforms.Normalize(mean=[0.406, 0.456, 0.485], std=[0.225, 0.224, 0.229])
#     ])

#     # ---- ํŒŒ์ผ ๋ฆฌ์ŠคํŠธ ๋งŒ๋“ค๊ธฐ (๋‹จ์ผ ํŒŒ์ผ/ํด๋” ๋ชจ๋‘ ๋Œ€์‘) ----
#     if input_path:
#         # root๋Š” ํŒŒ์ผ์˜ ๋ถ€๋ชจ ๋””๋ ‰ํ„ฐ๋ฆฌ, file_list๋Š” ํŒŒ์ผ๋ช… 1๊ฐœ
#         root = os.path.dirname(input_path)
#         file_list = [os.path.basename(input_path)]
#     else:
#         root = input_dir
#         file_list = sorted([
#             f for f in os.listdir(root)
#             if f.lower().endswith(('.png', '.jpg', '.jpeg'))
#         ])

#     dataset_obj = SimpleFolderDataset(
#         root=root,
#         input_size=input_size,
#         transform=transform,
#         file_list=file_list
#     )
#     dataloader = DataLoader(dataset_obj)

#     palette = get_palette(4)

#     results_img = []
#     results_logits = [] if logits else None
#     names = []

#     with torch.no_grad():
#         for batch in tqdm(dataloader):
#             image, meta = batch
#             img_name = meta['name'][0]
#             names.append(img_name)

#             c = meta['center'].numpy()[0]
#             s = meta['scale'].numpy()[0]
#             w = meta['width'].numpy()[0]
#             h = meta['height'].numpy()[0]

#             output = model(image.cuda())
#             upsample = torch.nn.Upsample(size=input_size, mode='bilinear', align_corners=True)
#             upsample_output = upsample(output[0][-1][0].unsqueeze(0))
#             upsample_output = upsample_output.squeeze()
#             upsample_output = upsample_output.permute(1, 2, 0)

#             logits_result = transform_logits(
#                 upsample_output.data.cpu().numpy(),
#                 c, s, w, h,
#                 input_size=input_size
#             )
#             parsing_result = np.argmax(logits_result, axis=2)

#             out_img = Image.fromarray(np.asarray(parsing_result, dtype=np.uint8))
#             out_img.putpalette(palette)
#             results_img.append(out_img)

#             if logits:
#                 results_logits.append(logits_result)

#     return {"images": results_img, "logits": results_logits, "names": names}




# def main():
#     # โœ… CLI ํ˜ธํ™˜ ์œ ์ง€
#     args = get_arguments()
#     run(
#         category=args.category,
#         input_dir=args.input_dir,
#         output_dir=args.output_dir,
#     )


# if __name__ == '__main__':
#     main()

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""
@Author  :   Peike Li
@Contact :   peike.li@yahoo.com
@File    :   simple_extractor.py
@Desc    :   Simple Extractor (category-aware palette selection)
"""

import os
import sys
import torch
import argparse
import numpy as np
from PIL import Image
from tqdm import tqdm

from torch.utils.data import DataLoader
import torchvision.transforms as transforms

_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
if _THIS_DIR not in sys.path:
    sys.path.insert(0, _THIS_DIR)

import networks
from utils.transforms import transform_logits
from datasets.simple_extractor_dataset import SimpleFolderDataset


dataset_settings = {
    'lip': {
        'input_size': [473, 473],
        'num_classes': 20,
        'label': [
            'Background', 'Hat', 'Hair', 'Glove', 'Sunglasses',
            'Upper-clothes', 'Dress', 'Coat', 'Socks', 'Pants',
            'Jumpsuits', 'Scarf', 'Skirt', 'Face',
            'Left-arm', 'Right-arm', 'Left-leg', 'Right-leg',
            'Left-shoe', 'Right-shoe'
        ]
    },
    'atr': {
        'input_size': [512, 512],
        'num_classes': 18,
        'label': [
            'Background', 'Hat', 'Hair', 'Sunglasses', 'Upper-clothes',
            'Skirt', 'Pants', 'Dress', 'Belt',
            'Left-shoe', 'Right-shoe', 'Face',
            'Left-leg', 'Right-leg', 'Left-arm', 'Right-arm',
            'Bag', 'Scarf'
        ]
    },
    'pascal': {
        'input_size': [512, 512],
        'num_classes': 7,
        'label': [
            'Background', 'Head', 'Torso',
            'Upper Arms', 'Lower Arms',
            'Upper Legs', 'Lower Legs'
        ],
    }
}


def get_arguments():
    parser = argparse.ArgumentParser(description="Self Correction for Human Parsing")

    parser.add_argument("--dataset", type=str, default='atr', choices=['lip', 'atr', 'pascal'])
    parser.add_argument("--model-restore", type=str, default='', help="restore pretrained model parameters.")
    parser.add_argument("--gpu", type=str, default='0', help="choose gpu device.")
    parser.add_argument("--category", type=str, default='Upper-cloth', help="category name.")
    parser.add_argument("--input-dir", type=str, default='', help="path of input image folder.")
    parser.add_argument("--output-dir", type=str, default='', help="(unused, kept for CLI compatibility)")
    parser.add_argument("--logits", action='store_true', default=False)

    return parser.parse_args()


def get_palette(num_cls):
    n = 18
    palette = [0] * (n * 3)
    j = num_cls
    lab = num_cls
    palette[j * 3 + 0] = 0
    palette[j * 3 + 1] = 0
    palette[j * 3 + 2] = 0
    while lab:
        palette[j * 3 + 0] = 255
        palette[j * 3 + 1] = 255
        palette[j * 3 + 2] = 255
        lab >>= 3
    return palette


def get_palette2(num_cls):
    n = 18
    palette = [0] * (n * 3)
    for j in range(5, 7):
        lab = j
        palette[j * 3 + 0] = 0
        palette[j * 3 + 1] = 0
        palette[j * 3 + 2] = 0
        while lab:
            palette[j * 3 + 0] = 255
            palette[j * 3 + 1] = 255
            palette[j * 3 + 2] = 255
            lab >>= 3
    return palette


def _select_palette_by_category(category: str):
    """
    category๋ณ„ palette ์„ ํƒ ๋กœ์ง (๋ช…์‹œ์  ๊ทœ์น™)
    """
    if category == "Upper-cloth":
        return get_palette(4)
    elif category == "Bottom":
        return get_palette2(4)
    elif category == "Dress":
        return get_palette(7)
    else:
        # fallback (๋ช…์‹œ ์•ˆ ๋œ ์นดํ…Œ๊ณ ๋ฆฌ)
        return get_palette(7)


def run(
    *,
    category: str,
    input_path: str = "",
    input_dir: str = "",
    dataset: str = "atr",
    model_restore: str = "",
    gpu: str = "0",
    logits: bool = False,
):
    """
    Returns:
        {
            "images": List[PIL.Image],
            "logits": Optional[List[np.ndarray]],
            "names": List[str],
        }
    """

    gpus = [int(i) for i in gpu.split(',')]
    assert len(gpus) == 1
    if gpu != 'None':
        os.environ["CUDA_VISIBLE_DEVICES"] = gpu

    if not model_restore:
        print("[simple_extractor] model_restore not provided โ†’ skip extractor.")
        return {"images": [], "logits": [] if logits else None, "names": []}

    if bool(input_path) == bool(input_dir):
        raise ValueError("Provide exactly one of input_path or input_dir.")

    if input_path and not os.path.isfile(input_path):
        raise FileNotFoundError(input_path)
    if input_dir and not os.path.isdir(input_dir):
        raise NotADirectoryError(input_dir)

    num_classes = dataset_settings[dataset]['num_classes']
    input_size = dataset_settings[dataset]['input_size']

    model = networks.init_model('resnet101', num_classes=num_classes, pretrained=None)
    state_dict = torch.load(model_restore)['state_dict']

    from collections import OrderedDict
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        new_state_dict[k[7:]] = v
    model.load_state_dict(new_state_dict)

    model.cuda()
    model.eval()

    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.406, 0.456, 0.485],
                             std=[0.225, 0.224, 0.229])
    ])

    if input_path:
        root = os.path.dirname(input_path)
        file_list = [os.path.basename(input_path)]
    else:
        root = input_dir
        file_list = sorted([
            f for f in os.listdir(root)
            if f.lower().endswith(('.png', '.jpg', '.jpeg'))
        ])

    dataset_obj = SimpleFolderDataset(
        root=root,
        input_size=input_size,
        transform=transform,
        file_list=file_list
    )
    dataloader = DataLoader(dataset_obj)

    # โœ… ํ•ต์‹ฌ ์ˆ˜์ •: category ๊ธฐ๋ฐ˜ palette ์„ ํƒ
    palette = _select_palette_by_category(category)

    results_img = []
    results_logits = [] if logits else None
    names = []

    with torch.no_grad():
        for batch in tqdm(dataloader):
            image, meta = batch
            img_name = meta['name'][0]
            names.append(img_name)

            c = meta['center'].numpy()[0]
            s = meta['scale'].numpy()[0]
            w = meta['width'].numpy()[0]
            h = meta['height'].numpy()[0]

            output = model(image.cuda())
            upsample = torch.nn.Upsample(
                size=input_size, mode='bilinear', align_corners=True
            )
            upsample_output = upsample(output[0][-1][0].unsqueeze(0))
            upsample_output = upsample_output.squeeze().permute(1, 2, 0)

            logits_result = transform_logits(
                upsample_output.data.cpu().numpy(),
                c, s, w, h,
                input_size=input_size
            )
            parsing_result = np.argmax(logits_result, axis=2)

            out_img = Image.fromarray(parsing_result.astype(np.uint8))
            out_img.putpalette(palette)
            results_img.append(out_img)

            if logits:
                results_logits.append(logits_result)

    return {
        "images": results_img,
        "logits": results_logits,
        "names": names
    }


def main():
    args = get_arguments()
    run(
        category=args.category,
        input_dir=args.input_dir,
        dataset=args.dataset,
        model_restore=args.model_restore,
        gpu=args.gpu,
        logits=args.logits,
    )


if __name__ == '__main__':
    main()