由于在学习的时候,要用到自己标注的样本,需要对样本进行人工标注生成mask图,在使用VGG Image Annotator(VIA)时对样本进行标注(这里不得不说这个网站挺好用的,还不需要下载,操作也简单),标注好之后,保存结果为xx.json文件,需要自己手动将其转换为mask图像,网上找了很多转换代码都不能达到自己的要求,于是自己将其总结,并重新写了能实现目标的代码,下面直接附上代码。
import os
import json
import numpy as np
import skimage.draw
import cv2
image_folder = r"D:\ProgramData\Anaconda3\pythonProject_1\bottle\test\contamination" #样本所在文件夹
mask_folder = "./mask/" #mask图像保存文件夹
path_annotation_json = 'box2.json'#.json文件
annotations = json.load(open(path_annotation_json, 'r'))#加载.json文件
imgs = annotations["_via_img_metadata"]
annotations = list(annotations.values())
annotations_point = annotations[1]
annotations_point = list(annotations_point.values())
annotations_point = [a for a in annotations_point if a['regions']]
for i in range(len(annotations_point)):#遍历图像样本
filename = annotations_point[i]['filename']
image_path = os.path.join(image_folder, filename)
image = cv2.imread(image_path)
height, width = image.shape[:2]
maskImage = np.zeros((height, width), dtype=np.uint8)
for j in range(len(annotations_point[i]['regions'])):#存在多个标注区域时,需要遍历
point = list(annotations_point[i]['regions'][j].values())[0]
point_x = point['all_points_x']
point_y = point['all_points_y']
rr, cc = skimage.draw.polygon(point_y, point_x)
maskImage[rr, cc] = 255 #生成mask黑白图
savePath = mask_folder + filename
cv2.imwrite(savePath, maskImage)#保存
示例