| import numpy as np | |
| import json | |
| import os | |
| from pycocotools import mask as maskUtils | |
| from PIL import Image | |
| from tqdm import tqdm | |
| import glob | |
| def singleMask2rle(mask): | |
| rle = maskUtils.encode(np.array(mask[:, :, None], order='F', dtype="uint8"))[0] | |
| rle["counts"] = rle["counts"].decode("utf-8") | |
| return rle | |
| def init_mapillary(base_image_dir): | |
| mapillary_data_root = os.path.join(base_image_dir, "mapillary") | |
| with open(os.path.join(mapillary_data_root, "config_v2.0.json")) as f: | |
| mapillary_classes = json.load(f)["labels"] | |
| mapillary_classes = [x["readable"].lower() for x in mapillary_classes] | |
| mapillary_classes = np.array(mapillary_classes) | |
| mapillary_labels = sorted( | |
| glob.glob( | |
| os.path.join(mapillary_data_root, "training", "v2.0", "labels", "*.png") | |
| ) | |
| ) | |
| mapillary_images = [ | |
| x.replace(".png", ".jpg").replace("v2.0/labels", "images") | |
| for x in mapillary_labels | |
| ] | |
| print("mapillary: ", len(mapillary_images)) | |
| return mapillary_classes, mapillary_images, mapillary_labels | |
| base_image_dir = '/mnt/workspace/workgroup/yuanyq/code/LISA/dataset' | |
| classes, images, labels = init_mapillary(base_image_dir) | |
| final_data = [] | |
| for idx in tqdm(range(len(images))): | |
| dic = {} | |
| image_path = images[idx] | |
| label_path = labels[idx] | |
| label = Image.open(label_path) | |
| label = np.array(label) | |
| unique_label = np.unique(label).tolist() | |
| if 255 in unique_label: | |
| unique_label.remove(255) | |
| if len(unique_label) == 0: | |
| continue | |
| cats = [] | |
| for class_id in unique_label: | |
| cats.append(classes[class_id]) | |
| masks = [] | |
| for class_id in unique_label: | |
| msk = label==class_id | |
| rle = singleMask2rle(msk) | |
| masks.append(rle) | |
| dic['image'] = image_path.replace('/mnt/workspace/workgroup/yuanyq/code/LISA/dataset/', '') | |
| dic['cat'] = cats | |
| dic['masks'] = masks | |
| final_data.append(dic) | |
| print(len(final_data)) | |
| with open('mapillary.json', 'w') as f: | |
| f.write(json.dumps(final_data)) |