最近正在学习深度学习中的图像分割,需要把使用labelme标记的多边形,转换成掩膜图片,经过参考多篇文章,发现需要使用labelme提供的json_to_dataset.py命令行工具,但操作比较麻烦而且不能支持批量转换,所以把代码整合了一下,做成了一个可执行的独立文件。

转换单张json标记命令行:

python labelme_gen_seg.py --json_file <json文件路径>

批量转换json命令行:

python labelme_gen_seg.py --json_dir <json目录路径>

labelme_gen_seg.py 源码如下,参考整合了labelme的相关源码:

import argparse
import base64
import json
import sys
import os
import os.path as osp
import io
import numpy as np
import math
import uuid
import globimport imgviz
import PIL.Imageimport logging
import base64def lbl_save(filename, lbl):if osp.splitext(filename)[1] != ".png":filename += ".png"# Assume label ranses [-1, 254] for int32,# and [0, 255] for uint8 as VOC.if lbl.min() >= -1 and lbl.max() < 255:lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode="P")colormap = imgviz.label_colormap()lbl_pil.putpalette(colormap.flatten())lbl_pil.save(filename)else:raise ValueError("[%s] Cannot save the pixel-wise class label as PNG. ""Please consider using the .npy format." % filename)def img_data_to_pil(img_data):f = io.BytesIO()f.write(img_data)img_pil = PIL.Image.open(f)return img_pildef img_data_to_arr(img_data):img_pil = img_data_to_pil(img_data)img_arr = np.array(img_pil)return img_arrdef img_b64_to_arr(img_b64):img_data = base64.b64decode(img_b64)img_arr = img_data_to_arr(img_data)return img_arrdef shape_to_mask(img_shape, points, shape_type=None, line_width=10, point_size=5
):mask = np.zeros(img_shape[:2], dtype=np.uint8)mask = PIL.Image.fromarray(mask)draw = PIL.ImageDraw.Draw(mask)xy = [tuple(point) for point in points]if shape_type == "circle":assert len(xy) == 2, "Shape of shape_type=circle must have 2 points"(cx, cy), (px, py) = xyd = math.sqrt((cx - px) ** 2 + (cy - py) ** 2)draw.ellipse([cx - d, cy - d, cx + d, cy + d], outline=1, fill=1)elif shape_type == "rectangle":assert len(xy) == 2, "Shape of shape_type=rectangle must have 2 points"draw.rectangle(xy, outline=1, fill=1)elif shape_type == "line":assert len(xy) == 2, "Shape of shape_type=line must have 2 points"draw.line(xy=xy, fill=1, width=line_width)elif shape_type == "linestrip":draw.line(xy=xy, fill=1, width=line_width)elif shape_type == "point":assert len(xy) == 1, "Shape of shape_type=point must have 1 points"cx, cy = xy[0]r = point_sizedraw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=1, fill=1)else:assert len(xy) > 2, "Polygon must have points more than 2"draw.polygon(xy=xy, outline=1, fill=1)mask = np.array(mask, dtype=bool)return maskdef shapes_to_label(img_shape, shapes, label_name_to_value):cls = np.zeros(img_shape[:2], dtype=np.int32)ins = np.zeros_like(cls)instances = []for shape in shapes:points = shape["points"]label = shape["label"]group_id = shape.get("group_id")if group_id is None:group_id = uuid.uuid1()shape_type = shape.get("shape_type", None)cls_name = labelinstance = (cls_name, group_id)if instance not in instances:instances.append(instance)ins_id = instances.index(instance) + 1cls_id = label_name_to_value[cls_name]mask = shape_to_mask(img_shape[:2], points, shape_type)cls[mask] = cls_idins[mask] = ins_idreturn cls, insdef parse_opt(known=False):parser = argparse.ArgumentParser()parser.add_argument('--json_file', default='', required=False,help='json file')parser.add_argument('--json_dir', default='', required=False,help='json directory')parser.add_argument('--out_dir', default='output', required=False,help='output directory')opt = parser.parse_known_args()[0] if known else parser.parse_args()return optdef seg_json_file(json_file,out_dir):json_name = osp.basename(json_file)json_name = json_name[:-5]out_dir = osp.join(out_dir, json_name)if not osp.exists(out_dir):os.makedirs(out_dir)data = json.load(open(json_file))imageData = data.get("imageData")if not imageData:imagePath = os.path.join(os.path.dirname(json_file), data["imagePath"])with open(imagePath, "rb") as f:imageData = f.read()imageData = base64.b64encode(imageData).decode("utf-8")img = img_b64_to_arr(imageData)label_name_to_value = {"_background_": 0}for shape in sorted(data["shapes"], key=lambda x: x["label"]):label_name = shape["label"]if label_name in label_name_to_value:label_value = label_name_to_value[label_name]else:label_value = len(label_name_to_value)label_name_to_value[label_name] = label_valuelbl, _ = shapes_to_label(img.shape, data["shapes"], label_name_to_value)label_names = [None] * (max(label_name_to_value.values()) + 1)for name, value in label_name_to_value.items():label_names[value] = namelbl_viz = imgviz.label2rgb(lbl, imgviz.asgray(img), label_names=label_names, loc="rb")PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))lbl_save(osp.join(out_dir, "label.png"), lbl)PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, "label_viz.png"))with open(osp.join(out_dir, "label_names.txt"), "w") as f:for lbl_name in label_names:f.write(lbl_name + "\n")logging.info("Saved to: {}".format(out_dir))def seg_json_dir(json_dir,out_dir):total_json = glob.glob(os.path.join(json_dir,'*.json'))for json_file in total_json:seg_json_file(json_file,out_dir)def main(opt):logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename='logs/labelme_gen_seg.log',filemode='w')console = logging.StreamHandler()console.setLevel(logging.INFO)logging.getLogger('').addHandler(console)if opt.json_file != '':seg_json_file(opt.json_file,opt.out_dir)elif opt.json_dir != '':seg_json_dir(opt.json_dir,opt.out_dir)else:logging.warning('NO ACTION DEFINED')if __name__ == "__main__":opt = parse_opt()main(opt)

批量转换labelme标记为掩膜图片相关推荐

  1. 批量转换图像格式Irfanview之CR2图片转Jpeg

    首先,在官网上下载Irfanview软件.注意下载的64位还是32位的,以便以后下载插件时,选着相应的版本. 其次,next式安装不需要就行修改,由于CR2需要安装插件,所以在插件页面搜索CR2插件下 ...

  2. docx文档怎么排列图片_格式转换太麻烦?仅需一行命令,搞定图片、音频、视频、文本批量转换!...

    每天12:18准时给大家惊喜! 大家好!我是好奇仔,热衷于搜罗和分享各种好用.实用的软件神器和资源,有手机软件.办公软件.APP,还有网站资源-- 来自:芒种学院(ID:lazy_info)  作者: ...

  3. 彩色图批量转换成灰度图、批量格式转换、批量重命名

    参考:http://blog.csdn.net/jjff46/article/details/38948621 代码实现的功能:把图片进行批量转换 (1)彩色图片转换成灰度图 (2)图片进行格式转换 ...

  4. 如何将webp批量转换jpg?

    如何将webp批量转换jpg?说到图片格式,大家首先想到的是jpg和png这两种常见的,随着计算机计算的发展涌现出了越来越多的图片格式,很多都是我们没有遇见过的,例如webp图片,第一次看到还以为是其 ...

  5. LabelMe标记后的json文件怎么转为COCO格式

    LabelMe标记后的json文件怎么转为COCO格式 步骤如下: Step 1: 下载labelme ,链接为https://github.com/wkentaro/labelme Step 2: ...

  6. 使用labelme标记图片、json批量转dataset的解决方案以及一些问题解决方案

    环境:win10+anaconda(python3.7) labelme 的安装 labelme的安装十分简单,只需要三行代码(首先打开anaconda prompt): conda create - ...

  7. labelme批量转换json

    安装:https://mp.csdn.net/postedit/80924918 使用:https://github.com/wkentaro/labelme 单张转换: labelme_json_t ...

  8. java批量转换图片格式

    废话不多直接上代码,代码其实也不多.... package com.qiao.testImage;import java.awt.image.BufferedImage; import java.io ...

  9. MATLAB对图片格式批量转换

    从网上下载一些数据集,发现是PPM或者PGM格式的,一般照片查看器打不开.可以用MATLAB对其进行批量转换格式.当然,任何两种格式之间相互转换都可以用这个程序: % 本示例程序将 pgm 图片转换为 ...

最新文章

  1. Docker安装Tomcat、MySQL和Redis
  2. 开发日记-20190806 关键词 读书笔记《Linux 系统管理技术手册(第二版)》DAY 20
  3. 微软管理控制台学习和创建自己的管理控制台
  4. 数据分析系统数据库选型
  5. 【Python笔记】网络爬虫——常用框架介绍以及 Scrapy 框架使用
  6. Fragment Transactions和Activity状态丢失
  7. 精心整理的10套最美Web前端新年特效---提前祝大家新年快乐(文末送书)
  8. CCF 201903-1 小中大
  9. 97-微服务项目的编写(上篇)
  10. ddl和dml(DDL和DML包含哪些动词)
  11. java鼠标左键点击四溅,重生之我是一只鼠
  12. 用Haskell写的卡普雷尔卡kaprekar黑洞小程序
  13. [关于Context]
  14. CAD2019中文版下载AutoCAD2019安装教程
  15. 国产GM8220,USB2.0集线器,替换汤铭的FE1.1,USB HUB,替换创维GL850
  16. 争对让望对思野葛对山栀注解_《笠翁对韵》上卷四支详解
  17. 删除流氓软件 Alibaba PC Safe Service
  18. 拼多多商家推广常见的问题解答。
  19. C#异常处理try catch
  20. 计算机软件蒋勇,西南科技大学考研研究生导师简介-蒋勇

热门文章

  1. scilab和matlab的区别,Fortran, Matlab, Octave, Scilab计算速度比较
  2. 关于AutoCAD启动速度慢的分析
  3. checked和unchecked的区别
  4. 微信小程序请求封装token
  5. js 高德地图,地图上落点,并点击地图上的图片可进行切换图片
  6. 浙江工业大学计算机考研科目,浙江工业大学考研专业目录
  7. Pascal 基础算法教案
  8. 互斥锁 、 自旋锁、读写锁和RCU锁
  9. 因果推断笔记——CV、机器人领域因果推断案例集锦(十)
  10. 2021年中国出口跨境电商行业融资态势及未来发展趋势分析[图]