0

i'm working whit labelme files in json files but .. How convert this files to mask files in png for U-net model ?

1 Answers1

0
import os
import cv2
import json
import glob
import numpy as np


#save all image files and json files separately to list
image_list = sorted(glob.glob('img_json/*.png'))
ann_list = sorted(glob.glob('img_json/*.json'))

#create blank mask with image sizes
def create_binary_masks(im, shape_dicts):
    
    blank = np.zeros(shape=(im.shape[0], im.shape[1]), dtype=np.float32)
    for shape in shape_dicts:
        points = np.array(shape['points'], dtype=np.int32)
        cv2.fillPoly(blank, [points], 255)
    return blank

#get annotated points
def get_poly(ann_path):
    
    with open(ann_path) as handle:
        data = json.load(handle)
    shape_dicts = data['shapes']
    
    return shape_dicts

#iterate every image and its json file to create binary mask
for im_fn, ann_fn in zip(image_list, ann_list):
    
    im = cv2.imread(im_fn, 0)
    shape_dicts = get_poly(ann_fn)
    im_binary = create_binary_masks(im, shape_dicts)
    
    #extract the name of image file
    filename = im_fn.split('.png')[-2].split('\\')[-1] + '.png'
    cv2.imwrite(filename, im_binary)

Here is the code I found and edited to match what you`re asking for. Just run this code with specification of your images and annotation folder. Usually all annotated images and their json files are saved in the same folder and have the same name. To successfully run this code you have to do as above. In the last code block where I run for loop to iterate through image and ann_list I saved binary masks with the same name as their images. Check carefully your path to extract filename using split

Sheroz
  • 1
  • 1