Skip to content

Instantly share code, notes, and snippets.

@ixtiyoruz
Created October 30, 2019 08:41
Show Gist options
  • Save ixtiyoruz/64f907314c298885a447e37368d943b1 to your computer and use it in GitHub Desktop.
Save ixtiyoruz/64f907314c298885a447e37368d943b1 to your computer and use it in GitHub Desktop.
Opening BDD dataset and saving it as a masked image
import json
import numpy as np
import os
import skimage
import cv2
import time
import scipy.misc
from PIL import Image
dataset_dir = "/media/ixtiyor/New Volume1/datasets/bdd/bdd100k_images/bdd100k/images/100k/"
input_dir = 'val'
annotations = json.load(open(os.path.join(os.path.join(dataset_dir, input_dir), "via_region_data.json")))
annotation_root = os.path.join(os.path.join(dataset_dir, "annotation"), input_dir)
def get_mask_from_polygons(polygon, height, width):
mask = np.zeros([height, width,3],
dtype=np.uint8)
#print ('mask shape',mask.shape)
for i, p in enumerate(polygon):
# print ('i',i)
# print ('p',p)
# Get indexes of pixels inside the polygon and set them to 1
x=[]
y=[]
for d in p:
for l in d['vertices']:
x.append(l[0])
y.append(l[1]-2)
# print ('x',x)
# print ('y',y)
rr, cc = skimage.draw.polygon(y,x)
print(x, y)
print(rr,cc)
mask[rr, cc] = [255,255,255]
# print(mask)
return mask
i = 0
categories = []
for a in annotations:
i += 1
start = time.time()
categories.extend([d['category'] for d in a['labels']])
# print(np.unique(categories))
polygons=[d['poly2d'] for d in a['labels'] if d['category']=="lane"]
# print(polygons)
image_path = os.path.join(dataset_dir, a['name'])
height, width = [720, 1280]#image.shape[:2]
# self.images.append(image_path)
img = get_mask_from_polygons(polygons,height, width)
# print(np.unique(img))
img = np.array(img)
# print(np.unique(img))
mask_path = os.path.join('/media/ixtiyor/087E6CE67E6CCDCE/annotation/',input_dir, a['name'].split('.')[0] +".png" )
# img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
# cv2.imwrite(mask_path, img, [cv2.IMWRITE_JPEG_QUALITY, 255])
# scipy.misc.toimage(img, cmin=0.0, cmax=255.0).save(mask_path)
# im = Image.fromarray(img,"RGB" )
# im.save(mask_path)
# read_image = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED)
# print(np.shape(img), type(img))
# np.save(mask_path,img)
# read_image = np.load(mask_path)
# print()
# print(i, "qolgan vaqt " , (time.time()-start) * (10000-i) * 1./60, " min")
# break
cv2.imshow("img", img)
if(cv2.waitKey(3) >0):break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment