Superimposed-Masked-Dataset / generate_occluded_imagenet_faster.py
ArielleE's picture
Upload 4 files
c4d7a2b
import os
import random
import numpy as np
import pandas as pd
from PIL import Image
from torchvision import datasets, transforms, io
import torch
def get_random_texture(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 the texture 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, image_width, image_height):
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 occlude_image(image, occluder_tensor, percentage_occlusion, occluded_dir, img_name):
occluder_pil = transforms.ToPILImage(mode='RGBA')(occluder_tensor)
occluder_pil = randomly_rotate_occluder(occluder_pil)
image_pil = transforms.ToPILImage()(image)
target_area = image_pil.width * image_pil.height * percentage_occlusion
occluder_pil = resize_occluder(occluder_pil, target_area, image_pil.width, image_pil.height)
if occluder_pil.width > image_pil.width or occluder_pil.height > image_pil.height:
pos = (image_pil.width // 2 - occluder_pil.width // 2,
image_pil.height // 2 - occluder_pil.height // 2)
else:
max_x = max(0, image_pil.width - occluder_pil.width)
max_y = max(0, image_pil.height - occluder_pil.height)
pos = (random.randint(0, max_x), random.randint(0, max_y))
image_pil.paste(occluder_pil, pos, occluder_pil)
image_with_occluder_tensor = transforms.ToTensor()(image_pil)
occluder_alpha = occluder_pil.getchannel('A')
binary_mask = Image.new('1', image_pil.size)
binary_mask.paste(occluder_alpha, pos, occluder_alpha)
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 = 'imagenet1'
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)
occlusion_info = pd.DataFrame(columns=["image_name", "class_name", "occluder_class",
"percentage_occlusion", "mask", "pos"])
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_texture(dataset_occluder)
occluded_image, mask_path, pos = occlude_image(image, occluder_tensor, 0.5, 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)
occlusion_info.to_csv(os.path.join(occluded_data_dir, "occlusion_info.csv"), index=False)
if __name__ == "__main__":
main()