File size: 12,602 Bytes
b213d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16c2627
 
b213d84
 
 
 
 
 
16c2627
b213d84
16c2627
b213d84
 
 
16c2627
b213d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from typing import Union

import cv2
import numpy as np
import torch
from diffusers.image_processor import VaeImageProcessor
from PIL import Image
from SCHP import SCHP  # type: ignore

from utils.densepose_for_mask import DensePose  # type: ignore

DENSE_INDEX_MAP = {
    "background": [0],
    "torso": [1, 2],
    "right hand": [3],
    "left hand": [4],
    "right foot": [5],
    "left foot": [6],
    "right thigh": [7, 9],
    "left thigh": [8, 10],
    "right leg": [11, 13],
    "left leg": [12, 14],
    "left big arm": [15, 17],
    "right big arm": [16, 18],
    "left forearm": [19, 21],
    "right forearm": [20, 22],
    "face": [23, 24],
    "thighs": [7, 8, 9, 10],
    "legs": [11, 12, 13, 14],
    "hands": [3, 4],
    "feet": [5, 6],
    "big arms": [15, 16, 17, 18],
    "forearms": [19, 20, 21, 22],
}

ATR_MAPPING = {
    "Background": 0,
    "Hat": 1,
    "Hair": 2,
    "Sunglasses": 3,
    "Upper-clothes": 4,
    "Skirt": 5,
    "Pants": 6,
    "Dress": 7,
    "Belt": 8,
    "Left-shoe": 9,
    "Right-shoe": 10,
    "Face": 11,
    "Left-leg": 12,
    "Right-leg": 13,
    "Left-arm": 14,
    "Right-arm": 15,
    "Bag": 16,
    "Scarf": 17,
}

LIP_MAPPING = {
    "Background": 0,
    "Hat": 1,
    "Hair": 2,
    "Glove": 3,
    "Sunglasses": 4,
    "Upper-clothes": 5,
    "Dress": 6,
    "Coat": 7,
    "Socks": 8,
    "Pants": 9,
    "Jumpsuits": 10,
    "Scarf": 11,
    "Skirt": 12,
    "Face": 13,
    "Left-arm": 14,
    "Right-arm": 15,
    "Left-leg": 16,
    "Right-leg": 17,
    "Left-shoe": 18,
    "Right-shoe": 19,
}

PROTECT_BODY_PARTS = {
    "upper": ["Left-leg", "Right-leg"],
    "lower": ["Right-arm", "Left-arm", "Face"],
    "overall": [],
    "inner": ["Left-leg", "Right-leg"],
    "outer": ["Left-leg", "Right-leg"],
}
PROTECT_CLOTH_PARTS = {
    "upper": {"ATR": ["Skirt", "Pants"], "LIP": ["Skirt", "Pants"]},
    "lower": {"ATR": ["Upper-clothes"], "LIP": ["Upper-clothes", "Coat"]},
    "overall": {"ATR": [], "LIP": []},
    "inner": {
        "ATR": ["Dress", "Coat", "Skirt", "Pants"],
        "LIP": ["Dress", "Coat", "Skirt", "Pants", "Jumpsuits"],
    },
    "outer": {
        "ATR": ["Dress", "Pants", "Skirt"],
        "LIP": ["Upper-clothes", "Dress", "Pants", "Skirt", "Jumpsuits"],
    },
}
MASK_CLOTH_PARTS = {
    "upper": ["Upper-clothes", "Coat", "Dress", "Jumpsuits"],
    "lower": ["Pants", "Skirt", "Dress", "Jumpsuits"],
    "overall": ["Upper-clothes", "Dress", "Pants", "Skirt", "Coat", "Jumpsuits"],
    "inner": ["Upper-clothes"],
    "outer": [
        "Coat",
    ],
}
MASK_DENSE_PARTS = {
    "upper": ["torso", "big arms", "forearms"],
    "lower": ["thighs", "legs"],
    "overall": ["torso", "thighs", "legs", "big arms", "forearms"],
    "inner": ["torso"],
    "outer": ["torso", "big arms", "forearms"],
}

schp_public_protect_parts = [
    "Hat",
    "Hair",
    "Sunglasses",
    "Left-shoe",
    "Right-shoe",
    "Bag",
    "Glove",
    "Scarf",
]
schp_protect_parts = {
    "upper": ["Left-leg", "Right-leg", "Skirt", "Pants", "Jumpsuits"],
    "lower": ["Left-arm", "Right-arm", "Upper-clothes", "Coat"],
    "overall": [],
    "inner": ["Left-leg", "Right-leg", "Skirt", "Pants", "Jumpsuits", "Coat"],
    "outer": ["Left-leg", "Right-leg", "Skirt", "Pants", "Jumpsuits", "Upper-clothes"],
}
schp_mask_parts = {
    "upper": ["Upper-clothes", "Dress", "Coat", "Jumpsuits"],
    "lower": ["Pants", "Skirt", "Dress", "Jumpsuits", "socks"],
    "overall": [
        "Upper-clothes",
        "Dress",
        "Pants",
        "Skirt",
        "Coat",
        "Jumpsuits",
        "socks",
    ],
    "inner": ["Upper-clothes"],
    "outer": [
        "Coat",
    ],
}

dense_mask_parts = {
    "upper": ["torso", "big arms", "forearms"],
    "lower": ["thighs", "legs"],
    "overall": ["torso", "thighs", "legs", "big arms", "forearms"],
    "inner": ["torso"],
    "outer": ["torso", "big arms", "forearms"],
}


def vis_mask(image, mask):
    image = np.array(image).astype(np.uint8)
    mask = np.array(mask).astype(np.uint8)
    mask[mask > 127] = 255
    mask[mask <= 127] = 0
    mask = np.expand_dims(mask, axis=-1)
    mask = np.repeat(mask, 3, axis=-1)
    mask = mask / 255
    return Image.fromarray((image * (1 - mask)).astype(np.uint8))


def part_mask_of(part: Union[str, list], parse: np.ndarray, mapping: dict):
    if isinstance(part, str):
        part = [part]
    mask = np.zeros_like(parse)
    for _ in part:
        if _ not in mapping:
            continue
        if isinstance(mapping[_], list):
            for i in mapping[_]:
                mask += parse == i
        else:
            mask += parse == mapping[_]
    return mask


def hull_mask(mask_area: np.ndarray):
    ret, binary = cv2.threshold(mask_area, 127, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(
        binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
    )
    hull_mask = np.zeros_like(mask_area)
    for c in contours:
        hull = cv2.convexHull(c)
        hull_mask = cv2.fillPoly(np.zeros_like(mask_area), [hull], 255) | hull_mask
    return hull_mask


class AutoMasker:
    def __init__(
        self,
        densepose_path: str = "./ckpts/densepose",
        schp_path: str = "./ckpts/schp",
        device="cuda",
    ):
        np.random.seed(0)
        torch.manual_seed(0)
        torch.cuda.manual_seed(0)

        self.densepose_processor = DensePose(densepose_path, device)
        self.schp_processor_atr = SCHP(
            ckpt_path=os.path.join(schp_path, "exp-schp-201908301523-atr.pth"),
            device=device,
        )
        self.schp_processor_lip = SCHP(
            ckpt_path=os.path.join(schp_path, "exp-schp-201908261155-lip.pth"),
            device=device,
        )

        self.mask_processor = VaeImageProcessor(
            vae_scale_factor=8,
            do_normalize=False,
            do_binarize=True,
            do_convert_grayscale=True,
        )

    def process_densepose(self, image_or_path):
        return self.densepose_processor(image_or_path, resize=1024)

    def process_schp_lip(self, image_or_path):
        return self.schp_processor_lip(image_or_path)

    def process_schp_atr(self, image_or_path):
        return self.schp_processor_atr(image_or_path)

    def preprocess_image(self, image_or_path):
        return {
            "densepose": self.densepose_processor(image_or_path, resize=1024),
            "schp_atr": self.schp_processor_atr(image_or_path),
            "schp_lip": self.schp_processor_lip(image_or_path),
        }

    @staticmethod
    def cloth_agnostic_mask(
        densepose_mask: Image.Image,
        schp_lip_mask: Image.Image,
        schp_atr_mask: Image.Image,
        part: str = "overall",
        **kwargs,
    ):
        assert part in [
            "upper",
            "lower",
            "overall",
            "inner",
            "outer",
        ], f"part should be one of ['upper', 'lower', 'overall', 'inner', 'outer'], but got {part}"
        w, h = densepose_mask.size

        dilate_kernel = max(w, h) // 250
        dilate_kernel = dilate_kernel if dilate_kernel % 2 == 1 else dilate_kernel + 1
        dilate_kernel = np.ones((dilate_kernel, dilate_kernel), np.uint8)

        kernal_size = max(w, h) // 25
        kernal_size = kernal_size if kernal_size % 2 == 1 else kernal_size + 1

        densepose_mask = np.array(densepose_mask)
        schp_lip_mask = np.array(schp_lip_mask)
        schp_atr_mask = np.array(schp_atr_mask)

        # Strong Protect Area (Hands, Face, Accessory, Feet)
        hands_protect_area = part_mask_of(
            ["hands", "feet"], densepose_mask, DENSE_INDEX_MAP
        )
        hands_protect_area = cv2.dilate(hands_protect_area, dilate_kernel, iterations=1)
        hands_protect_area = hands_protect_area & (
            part_mask_of(
                ["Left-arm", "Right-arm", "Left-leg", "Right-leg"],
                schp_atr_mask,
                ATR_MAPPING,
            )
            | part_mask_of(
                ["Left-arm", "Right-arm", "Left-leg", "Right-leg"],
                schp_lip_mask,
                LIP_MAPPING,
            )
        )
        face_protect_area = part_mask_of("Face", schp_lip_mask, LIP_MAPPING)

        strong_protect_area = hands_protect_area | face_protect_area

        # Weak Protect Area (Hair, Irrelevant Clothes, Body Parts)
        body_protect_area = part_mask_of(
            PROTECT_BODY_PARTS[part], schp_lip_mask, LIP_MAPPING
        ) | part_mask_of(PROTECT_BODY_PARTS[part], schp_atr_mask, ATR_MAPPING)
        hair_protect_area = part_mask_of(
            ["Hair"], schp_lip_mask, LIP_MAPPING
        ) | part_mask_of(["Hair"], schp_atr_mask, ATR_MAPPING)
        cloth_protect_area = part_mask_of(
            PROTECT_CLOTH_PARTS[part]["LIP"], schp_lip_mask, LIP_MAPPING
        ) | part_mask_of(PROTECT_CLOTH_PARTS[part]["ATR"], schp_atr_mask, ATR_MAPPING)
        accessory_protect_area = part_mask_of(
            (
                accessory_parts := [
                    "Hat",
                    "Glove",
                    "Sunglasses",
                    "Bag",
                    "Left-shoe",
                    "Right-shoe",
                    "Scarf",
                    "Socks",
                ]
            ),
            schp_lip_mask,
            LIP_MAPPING,
        ) | part_mask_of(accessory_parts, schp_atr_mask, ATR_MAPPING)
        weak_protect_area = (
            body_protect_area
            | cloth_protect_area
            | hair_protect_area
            | strong_protect_area
            | accessory_protect_area
        )

        # Mask Area
        strong_mask_area = part_mask_of(
            MASK_CLOTH_PARTS[part], schp_lip_mask, LIP_MAPPING
        ) | part_mask_of(MASK_CLOTH_PARTS[part], schp_atr_mask, ATR_MAPPING)
        background_area = part_mask_of(
            ["Background"], schp_lip_mask, LIP_MAPPING
        ) & part_mask_of(["Background"], schp_atr_mask, ATR_MAPPING)
        mask_dense_area = part_mask_of(
            MASK_DENSE_PARTS[part], densepose_mask, DENSE_INDEX_MAP
        )
        mask_dense_area = cv2.resize(
            mask_dense_area.astype(np.uint8),
            None,
            fx=0.25,
            fy=0.25,
            interpolation=cv2.INTER_NEAREST,
        )
        mask_dense_area = cv2.dilate(mask_dense_area, dilate_kernel, iterations=2)
        mask_dense_area = cv2.resize(
            mask_dense_area.astype(np.uint8),
            None,
            fx=4,
            fy=4,
            interpolation=cv2.INTER_NEAREST,
        )

        mask_area = (
            np.ones_like(densepose_mask) & (~weak_protect_area) & (~background_area)
        ) | mask_dense_area

        mask_area = (
            hull_mask(mask_area * 255) // 255
        )  # Convex Hull to expand the mask area
        mask_area = mask_area & (~weak_protect_area)
        mask_area = cv2.GaussianBlur(mask_area * 255, (kernal_size, kernal_size), 0)
        mask_area[mask_area < 25] = 0
        mask_area[mask_area >= 25] = 1
        mask_area = (mask_area | strong_mask_area) & (~strong_protect_area)
        mask_area = cv2.dilate(mask_area, dilate_kernel, iterations=1)

        return Image.fromarray(mask_area * 255)

    def __call__(
        self,
        image: Union[str, Image.Image],
        mask_type: str = "upper",
    ):
        assert mask_type in [
            "upper",
            "lower",
            "overall",
            "inner",
            "outer",
        ], f"mask_type should be one of ['upper', 'lower', 'overall', 'inner', 'outer'], but got {mask_type}"
        preprocess_results = self.preprocess_image(image)
        mask = self.cloth_agnostic_mask(
            preprocess_results["densepose"],
            preprocess_results["schp_lip"],
            preprocess_results["schp_atr"],
            part=mask_type,
        )
        return {
            "mask": mask,
            "densepose": preprocess_results["densepose"],
            "schp_lip": preprocess_results["schp_lip"],
            "schp_atr": preprocess_results["schp_atr"],
        }


if __name__ == "__main__":
    import os
    import sys

    from PIL import Image

    automasker = AutoMasker()

    image_path = sys.argv[1]
    image = Image.open(image_path).convert("RGB")
    outputs = automasker(
        image,
        "upper",
        # "lower",
    )
    mask = outputs["mask"]
    # densepose = outputs["densepose"]  # densepose I map, range 0~24
    # schp_lip = outputs["schp_lip"]
    # schp_atr = outputs["schp_atr"]
    mask.save(".".join(image_path.split(".")[:-1]) + "_mask.jpg")