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()