摘要:
labelme是常用的标注工具,由于最近要用到示例分割的模型,需要把labelme的polygon格式转为mask,这里用与复旦行人检测数据集类似的方式生成mask,即:背景像素值0,目标物体像素值根据目标个数依次确定,如:有两个物体则像素值依次为1,2,有5个物体则依次为1,2,3,4,5.
重写也不是很困难但是某些小细节上可能会坑你好久,造个轮子后面直接用。
源码
import cv2 as cv
import numpy as np
import json
import os
def convertPolygonToMask(jsonfilePath):
with open(jsonfilePath, "r", encoding='utf-8') as jsonf:
jsonData = json.load(jsonf)
img_h = jsonData["imageHeight"]
img_w = jsonData["imageWidth"]
mask = np.zeros((img_h, img_w), np.uint8)
#图片中目标的数量 num=len(jsonData["shapes"])
num = 0
for obj in jsonData["shapes"]:
label = obj["label"]
polygonPoints = obj["points"]
polygonPoints = np.array(polygonPoints,np.int32)
# print("+" * 50, "\n", polygonPoints)
# print(label)
num+=1
cv.drawContours(mask,[polygonPoints],-1,(255),-1)
return mask
def main():
jsonfileFolder = r"K:\imageData\colorR\dataset\label"
maskSaveFolder = r"K:\imageData\colorR\dataset\mask"
for jsonfile in os.listdir(jsonfileFolder):
jsonfilePath = os.path.join(jsonfileFolder,jsonfile)
mask = convertPolygonToMask(jsonfilePath)
maskName = jsonfile.split(".")[0] + ".png"
maskPath = os.path.join(maskSaveFolder,maskName)
cv.imwrite(maskPath,mask)
if __name__ == "__main__":
#main()
jsonfilePath = r"K:\deepImage\del\1.json"
maskSaveFolder = r"K:\deepImage\del"
mask = convertPolygonToMask(jsonfilePath)
# 为了可视化把mask做一下阈值分割
_, th = cv.threshold(mask, 0, 255, cv.THRESH_BINARY)
cv.imshow("mask", th)
src = cv.imread(r"K:\deepImage\del\1.jpg")
cv.imwrite(maskSaveFolder + "\mask.png", mask)
cv.imshow("src", src)
cv.waitKey(0)
cv.destroyAllWindows()
示例
-
对比
-
mask保存后用3D surface显示如下