lkstore / gs_kubric /merge_all_masks.py
lkeab's picture
update
8eeedfe
import os
from os import path
import numpy as np
import PIL
from PIL import Image
from packaging import version
import sys
import torch
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
PIL_INTERPOLATION = {
"linear": PIL.Image.Resampling.BILINEAR,
"bilinear": PIL.Image.Resampling.BILINEAR,
"bicubic": PIL.Image.Resampling.BICUBIC,
"lanczos": PIL.Image.Resampling.LANCZOS,
"nearest": PIL.Image.Resampling.NEAREST,
}
else:
PIL_INTERPOLATION = {
"linear": PIL.Image.LINEAR,
"bilinear": PIL.Image.BILINEAR,
"bicubic": PIL.Image.BICUBIC,
"lanczos": PIL.Image.LANCZOS,
"nearest": PIL.Image.NEAREST,
}
ROOT = '/projects/katefgroup/datasets/gs_kubric/InpaintingFormat_Set50'
OUT_ROOT = os.path.join(ROOT)
RESOLUTION = 512
mask_dir = path.join(ROOT, 'Annotations')
image_dir = path.join(ROOT, 'JPEGImages')
videos = []
num_frames = {}
num_objects = {}
vid_names = os.listdir(image_dir)
for _video in vid_names:
videos.append(_video)
num_frames[_video] = len(os.listdir(path.join(image_dir, _video)))
num_objects[_video] = len(os.listdir(path.join(mask_dir, _video)))
for index in range(len(videos)):
video = videos[index]
num_objs = num_objects[video]
os.makedirs(os.path.join(os.path.join(OUT_ROOT, 'MergedAnnotations', video)), exist_ok=True)
img_file_names = os.listdir(path.join(image_dir, video))
for f in range(num_frames[video]):
# Load RGBs
file_name = img_file_names[f]
img_file = path.join(image_dir, video, file_name)
img = Image.open(img_file).convert('RGB')
img = img.resize((RESOLUTION, RESOLUTION))
binary_masks = np.zeros((2, RESOLUTION, RESOLUTION))
for i in range(num_objs):
mask_file = path.join(mask_dir, video, str(i).zfill(3), file_name[:-4]+".png")
mask = Image.open(mask_file).convert("RGB")
mask = mask.resize((RESOLUTION, RESOLUTION), PIL_INTERPOLATION["nearest"])
mask = np.array(mask)[:, :, 0]
if i != 0:
binary_masks[1] += (mask > 128)
binary_masks[1] = np.clip(binary_masks[1], 0, 1)
else:
binary_masks[i] = (mask > 128)
obj_id = 0
for _ in range(2):
os.makedirs(os.path.join(os.path.join(OUT_ROOT, 'MergedAnnotations', video, str(obj_id).zfill(3))), exist_ok=True)
Image.fromarray(binary_masks[obj_id].astype(np.uint8) * 255).save(os.path.join(OUT_ROOT, 'MergedAnnotations', video, str(obj_id).zfill(3), file_name[:-4]+".png"))
obj_id += 1