Qupath得到的json标注转化为mask
CSDN中大部分都是labelme的,假如你的json文件也是如下的格式,并且分割的mask中类别只有1类即0,1:
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[403, 829],
[400, 830],
[397, 830],
[1013, 321]
]
[
[3, 82],
[30, 83],
[97, 80],
[13, 32]
]
]
}
那么就可以使用下面的代码转化为mask,在dataset_dir
中放json文件夹目录,save_dir
放mask保存的文件夹,mask_size
设置mask的大小,一般设置为与原图像大小一致。每个数组中,第一个为整体,第二个为整体中间含有的背景,所以代码中将第一个设为前景,第二个及以后设为背景。
倒数第二行的mask = mask/255
将每个pixel值设为1,如果需要可视化,可直接注释掉这行,那么生成的图会将前景设为白色
import cv2
import json
import os
import numpy as np
import re
import shutil
from tqdm import tqdm
dataset_dir = r"path_to_json/"
save_dir = r"path_mask_to_save/"
mask_size = (1024,1024)
label_path = []
def is_2d_list(lst):
if isinstance(lst, list) and all(isinstance(sublist, list) for sublist in lst):
return len(set(len(sublist) for sublist in lst)) == 1
return False
for i in os.listdir(dataset_dir):
if i.endswith(".json"):
label_path.append(dataset_dir + "/" + i)
for c, i in tqdm(enumerate(label_path), total=len(label_path)):
mask = np.zeros(mask_size , dtype=np.uint8)
mask[mask>0] = 0
com_name = label_path[c].split('//')[-1].split('.')[0]
with open(i) as f:
data_ = json.load(f)
for data in data_:
data = np.array(data["geometry"]["coordinates"])
if np.array(data[0]).ndim == 2:
for j in range(len(data)):
poly = data[j]
poly = np.array(poly)
if j == 0:
poly = np.array(poly)
mask = cv2.fillPoly(mask, np.int32([poly]), color=(255, 255, 255))
else:
poly = np.array(poly)
mask = cv2.fillPoly(mask, np.int32([poly]), color=(0, 0, 0))
elif np.array(data[0][0]).ndim == 2:
print(i)
for j in range(len(data[0])):
# print(np.array(x).shape)
poly = data[0][j]
poly = np.array(poly)
if j == 0:
poly = np.array(poly)
mask = cv2.fillPoly(mask, np.int32([poly]), color=(255, 255, 255))
else:
poly = np.array(poly)
mask = cv2.fillPoly(mask, np.int32([poly]), color=(0, 0, 0))
mask = mask/255
cv2.imwrite(save_dir + com_name + ".png", mask)
注释掉mask = mask/255
最后可以得到这样的一个mask