赞
踩
核心思想:“将颜色转换成对应的标号”
形式一:Json格式的标注转换成调色板mask
形式二:RGB类型mask(24位三通道)转成调色板mask(8位单通道),调色板的格式为.png
形式三:对于二分类的语义分割,一般采用灰度图(8位单通道)
首先读取json文件,获取获取图片width和height ,使用构造三个东西:调色板mask,colormap(一维列表),类别列表(含背景),类别索引
import numpy as np from PIL import Image,ImageDraw import json #一张图片对应一个json文件的情况 def json2mask(json_path,colormap): #打开json 文件 with open(json_path,"r",encoding="utf-8") as f: #获取字典 data=json.load(f) #获取所有标注的多边形 shapes=data["shapes"] height=data["imageHeight"] width=data["imageWidth"] #构造mask,大小和原图大小一致 mask=Image.new("P",(width,height),0) mask.putpalette(colormap) #获取图像路径 image_path=data["imagePath"] for shape in shapes: label_index=int(shape["label"]) #类别索引 points=shape["points"] #列表 points=[ tuple(points[i]) for i in range(len(points))] #print(points) drawObject=ImageDraw.Draw(mask) drawObject.polygon(points,fill=label_index) #调色板模式需要用.png存储,所以这里需要对图像的格式进行检查 if image_path.endswith("jpg") is True: image_path=image_path.split(".")[0]+".png" mask.save(image_path) # mask=np.array(mask) # print(mask[1000:1060,10:100]) if __name__=="__main__": #classes长度为类别数加一 例如我有猫,狗,树三个种类,加上background后就是四类 #构造调色板的颜色,颜色种类和classes的种类一致,每三位代表一种颜色例如 0,0,0 为黑色,128,0,0 为红色,0,128,0为绿色,0,0,128为蓝色 colormap=[0,0,0,128,0,0,0,128,0,0,0,128] json_path="./segmentation.json" json2mask(json_path=json_path,colormap=colormap)
参考:https://blog.csdn.net/qq_37541097/article/details/113247318?spm=1001.2014.3001.5502
B站李沐老师的语义分割视频
import numpy as np from PIL import Image,ImageDraw import json def json2mask(json_path): #打开json 文件 with open(json_path,"r",encoding="utf-8") as f: #获取字典 data=json.load(f) #获取所有需要的信息 images=data["images"] annotations=data["annotations"] for i in range(len(images)): #图像的名称 image_name=images[i]["file_name"].split("/")[-1] image_width=images[i]["width"] image_height=images[i]["height"] #多边形标注点 points=annotations[i]["segmentation"][0] #[(x1,y1),(x2,y2),........] points=[ (points[i],points[i+1]) for i in range(0,len(points),2)] #构造mask,大小和原图大小一致,模式设置为RGB,颜色为黑色 new_image_mask=Image.new("RGB",(image_width,image_height),"black") # 接下来进行填充 drawObject=ImageDraw.Draw(new_image_mask) drawObject.polygon(points,fill="white") new_image_mask.save(image_name) if __name__=="__main__": json_path="./instances_default.json" json2mask(json_path=json_path)
https://zhuanlan.zhihu.com/p/22976342
https://www.cnpython.com/qa/70742
https://blog.csdn.net/Return_0_/article/details/97623422
image缩放使用插值
mask缩放使用就近插值,即使用周围图像填充
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。