File size: 7,374 Bytes
c4d7a2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import random
import numpy as np
import pandas as pd
from PIL import Image
from torchvision import datasets, transforms, io


def get_random_occluder(dataset_occluder):
    index = random.randint(0, len(dataset_occluder) - 1)
    texture_path, texture_class_index = dataset_occluder.imgs[index]
    texture_class = dataset_occluder.classes[texture_class_index]

    # load with the alpha channel
    texture = io.read_image(texture_path, mode=io.image.ImageReadMode.RGB_ALPHA)

    return texture, texture_class


def resize_occluder(occluder_pil, target_area):
    alpha = np.array(occluder_pil.getchannel('A'))
    non_transparent_area = np.count_nonzero(alpha > 0)

    area_scale_factor = target_area / non_transparent_area

    width_scale_factor = np.sqrt(area_scale_factor * (occluder_pil.width / occluder_pil.height))
    height_scale_factor = np.sqrt(area_scale_factor * (occluder_pil.height / occluder_pil.width))

    new_width = occluder_pil.width * width_scale_factor
    new_height = occluder_pil.height * height_scale_factor

    resized_occluder = occluder_pil.resize((int(new_width), int(new_height)), Image.LANCZOS)

    return resized_occluder


def randomly_rotate_occluder(occluder_pil):
    angle = random.uniform(-180, 180)
    return occluder_pil.rotate(angle, resample=Image.BICUBIC, expand=True)


def calculate_distance(point1, point2):
    x1, y1 = point1
    x2, y2 = point2
    return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5


def try_rotations(occluder_pil, image_pil, target_area, pos1=None):
    best_occluder = None
    best_area = 0
    best_pos = None
    min_distance = 130 # min distance if two occluders
    for _ in range(75):  # increase number of attempts to find better position
        rotated = randomly_rotate_occluder(occluder_pil)
        resized = resize_occluder(rotated, target_area)
        if resized.width > image_pil.width or resized.height > image_pil.height:
            pos = (image_pil.width // 2 - resized.width // 2, 
                   image_pil.height // 2 - resized.height // 2)
        else:
            max_x = max(0, image_pil.width - resized.width)
            max_y = max(0, image_pil.height - resized.height)
            pos = (random.randint(0, max_x), random.randint(0, max_y))

        if pos1 is not None and calculate_distance(pos1, pos) < min_distance:
            continue

        mask = Image.new('1', image_pil.size)
        mask.paste(resized.getchannel('A'), pos, resized.getchannel('A'))
        area = np.count_nonzero(np.array(mask))

        if area > best_area:
            best_area = area
            best_occluder = resized
            best_pos = pos
          
    return best_occluder, best_pos


def occlude_image(image, occluder_tensor, percentage_occlusion, occluded_dir, img_name):
    occluder_pil = transforms.ToPILImage(mode='RGBA')(occluder_tensor)
    image_pil = transforms.ToPILImage()(image)

    binary_mask = Image.new('1', image_pil.size)
    
    rn = random.random()

    if rn < 0.5:  # randomly use two occluders
        occluder_resizing_factor = 0.5
    else:
        occluder_resizing_factor = 1.0

    target_area = image_pil.width * image_pil.height * percentage_occlusion * occluder_resizing_factor

    if rn < 0.5:  # randomly use two occluders (can make this k occluders)
        occluder_pil1, pos1 = try_rotations(occluder_pil, image_pil, target_area / 2)
        image_pil.paste(occluder_pil1, pos1, occluder_pil1)
        occluder_alpha1 = occluder_pil1.getchannel('A')
        binary_mask.paste(occluder_alpha1, pos1, occluder_alpha1)
        
        occluder_pil2, pos2 = try_rotations(occluder_pil, image_pil, target_area / 2, pos1)
        if occluder_pil2 is not None and pos2 is not None:
            image_pil.paste(occluder_pil2, pos2, occluder_pil2)
            occluder_alpha2 = occluder_pil2.getchannel('A')
            binary_mask.paste(occluder_alpha2, pos2, occluder_alpha2)
        
        if pos2 is None:
            pos = [pos1]
        else:
            pos = [pos1, pos2]
    else:
        occluder_pil, pos = try_rotations(occluder_pil, image_pil, target_area)
        image_pil.paste(occluder_pil, pos, occluder_pil)
        occluder_alpha = occluder_pil.getchannel('A')
        binary_mask.paste(occluder_alpha, pos, occluder_alpha)

        pos = [pos]

    image_with_occluder_tensor = transforms.ToTensor()(image_pil)

    mask_array = np.array(binary_mask)
    mask_path = os.path.join(occluded_dir, f"{img_name}_mask.npy")
    np.save(mask_path, mask_array)

    return image_with_occluder_tensor, mask_path, pos


def rebuild_display_mask(image_path, mask_path):
    image_pil = Image.open(image_path)
    binary_mask = Image.new('1', image_pil.size)

    mask_array = np.load(mask_path)
    mask_indices = np.transpose(np.nonzero(mask_array))

    for i, j in mask_indices:
        binary_mask.putpixel((j, i), 1)

    binary_mask.show()


def build_dataset(data_path, transform):
    dataset = datasets.ImageFolder(data_path, transform=transform)
    nb_classes = len(dataset.classes)
    return dataset, nb_classes


def build_transform():
    t = []
    t.append(transforms.ToTensor())
    return transforms.Compose(t)


def main():
    data_dir = 'imagenet'
    texture_dir = 'occluders_segmented'
    occluded_data_dir = 'imagenet_occluded'

    transform = build_transform()
    dataset, nb_classes = build_dataset(data_dir, transform)
    dataset_occluder, _ = build_dataset(texture_dir, transform)
    percentage_occlusion = 0.3 # ~30%

    occlusion_info = pd.DataFrame(columns=["image_name", "class_name", "occluder_class",
                                           "percentage_occlusion", "mask", "pos"])
    
    count = 0

    for idx in range(len(dataset)):
        image, label = dataset[idx]
        category = dataset.classes[label]

        in_dir = os.path.join(data_dir, category)
        occluded_dir = os.path.join(occluded_data_dir, category)

        os.makedirs(occluded_dir, exist_ok=True)

        img_name = dataset.imgs[idx][0].split('/')[-1].split('.')[0]

        occluder_tensor, occluder_class = get_random_occluder(dataset_occluder)
        occluded_image, mask_path, pos = occlude_image(image, occluder_tensor, 
                                                       percentage_occlusion,
                                                       occluded_dir,
                                                       img_name)

        mask_array = np.load(mask_path)
        actual_percentage_occlusion = np.count_nonzero(mask_array) / (image.shape[1] * image.shape[2])

        occluded_image_path = os.path.join(occluded_dir, f"{img_name}_occluded.png")
        transforms.ToPILImage()(occluded_image).save(occluded_image_path)

        new_row = pd.DataFrame({
            "image_name": [f"{img_name}_occluded.png"],
            "class_name": [category],
            "occluder_class": [occluder_class],
            "percentage_occlusion": [actual_percentage_occlusion],
            "mask": [mask_path],
            "pos": [pos]
        })

        occlusion_info = pd.concat([occlusion_info, new_row], ignore_index=True)
        if count % 50 == 0: 
            print("Folder: {}/1000 ({})".format(count / 50, category))
        count+=1

    occlusion_info.to_csv(os.path.join(occluded_data_dir, "occlusion_info.csv"), index=False)

if __name__ == "__main__":
    main()