我正在处理json文件中的labelme文件,但是..如何将此文件转换为U-net模型的png格式的掩码文件?
发布于 2021-11-09 02:17:32
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)
这是我找到并编辑的代码,以符合您的要求。只需使用指定的图像和注释文件夹运行此代码即可。通常,所有带注释的图像及其json文件都保存在相同的文件夹中,并具有相同的名称。要成功运行这段代码,您必须执行上述操作。在最后一个代码块中,我运行for循环来迭代图像和ann_list,我保存了与它们的图像同名的二进制掩码。使用split仔细检查您的路径以提取文件名
https://stackoverflow.com/questions/66835020
复制