Labelme标注标签文件转png图像代码

import argparse
import base64
import json
import os
import os.path as osp

import imgviz
import PIL.Image

from labelme.logger import logger
from labelme import utils


def main(paths, b):
    logger.warning(
        "This script is aimed to demonstrate how to convert the "
        "JSON file to a single image dataset."
    )
    logger.warning(
        "It won't handle multiple JSON files to generate a "
        "real-use dataset."
    )

    parser = argparse.ArgumentParser()
    # parser.add_argument("json_file")
    parser.add_argument("-json_file", default = paths)
    parser.add_argument("-o", "--out", default=None)
    args = parser.parse_args()

    json_file = args.json_file

    if args.out is None:
        out_dir = osp.basename(json_file).replace(".", "_")
        out_dir = osp.join(osp.dirname(json_file), out_dir)
    else:
        out_dir = args.out
    if not osp.exists(out_dir):
        os.mkdir(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 = utils.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_value
    lbl, _ = utils.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] = name

    lbl_viz = imgviz.label2rgb(
        lbl, imgviz.asgray(img), label_names=label_names, loc="rb"
    )

    PIL.Image.fromarray(img).save(osp.join(out_dir, "img.png"))
    utils.lblsave(osp.join(out_dir, "label.png"), lbl)
    save_file = '/Users/dhf/Desktop/bjD/save'
    utils.lblsave(osp.join(save_file, b + ".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")

    logger.info("Saved to: {}".format(out_dir))


if __name__ == "__main__":
    path = '/Users/dhf/Desktop/bjD/bjD_Crop_json/'
    filelist = os.listdir(path) #获取文件路径
    for item in filelist:
            #if item.endswith('.jpg'):  #初始的图片的格式为jpg格式的(或者源文件是png格式及其他格式,后面的转换格式就可以调整为自己需要的格式即可)
            paths = path + item
            b = item.split('/')[-1]
            b = b.split('.')[0]
            print("b:",b)
            print("paths:",paths)
            main(paths,b)
    # main()

将生成的png图像转灰度标签文件

import os
#import Image
import PIL.Image as Image
import numpy as np

def Mode_P_to_L(img_file,stretch_value):

    file_name_list = os.listdir(img_file)
    #path_save = 'C:/Users/Hasee/Desktop/bjD/save_gray'
    path_save = '/Users/dhf/Desktop/bjD/save_gray'
    for file in file_name_list:
        img_path = os.path.join(img_file, file)
        image = Image.open(img_path)
        #print(image.mode)
        img_arry = Image.fromarray(np.uint8(image))
        #print(img_arry.mode)
        img_L = img_arry.convert("L")
        #print(img_L.mode)

        img_end = Image.fromarray(np.uint8(img_L) * stretch_value)
        #print(img_end.mode)
        #save_name = os.path.join(img_file, 'gray_'+file)
        save_name = os.path.join(path_save, file)
        img_end.save(save_name)
        #print(save_name)
if __name__ == '__main__':
    #path = 'C:/Users/Hasee/Desktop/bjC/save'
    path = '/Users/dhf/Desktop/bjD/save'
    Mode_P_to_L(path,1)

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用labelme的官方工具labelme2voc将json文件化为VOC格式的标注文件,然后使用VOC格式的标注文件生成灰度的png图像。 具体步骤如下: 1. 安装labelme2voc 可以使用pip安装: ``` pip install labelme2voc ``` 2. 将json文件化为VOC格式的标注文件 使用labelme2voc命令将json文件化为VOC格式的标注文件: ``` labelme2voc input_json_dir output_voc_dir ``` 其中,input_json_dir是存放json文件的目录路径,output_voc_dir是输出VOC格式标注文件的目录路径。 例如,有一个json文件存放在/home/user/data/json目录下,要将其化为VOC格式标注文件并存放在/home/user/data/voc目录下,可以执行以下命令: ``` labelme2voc /home/user/data/json /home/user/data/voc ``` 执行完毕后,会在输出目录下生成与json文件对应的VOC格式标注文件。 3. 将VOC格式标注文件生成灰度的png图像 可以使用VOC格式标注文件生成灰度的png图像的工具有很多,例如opencv、PIL等。 以opencv为例,可以使用以下代码将VOC格式标注文件生成灰度的png图像: ``` import cv2 import os input_voc_dir = "/home/user/data/voc" output_gray_dir = "/home/user/data/gray" if not os.path.exists(output_gray_dir): os.makedirs(output_gray_dir) for filename in os.listdir(input_voc_dir): if filename.endswith(".xml"): xml_file = os.path.join(input_voc_dir, filename) img_file = xml_file.replace(".xml", ".jpg") img = cv2.imread(img_file) h, w = img.shape[:2] gray = np.zeros((h, w), np.uint8) tree = ET.parse(xml_file) for obj in tree.findall("object"): name = obj.find("name").text bndbox = obj.find("bndbox") xmin = int(bndbox.find("xmin").text) ymin = int(bndbox.find("ymin").text) xmax = int(bndbox.find("xmax").text) ymax = int(bndbox.find("ymax").text) gray[ymin:ymax, xmin:xmax] = 255 if name == "target" else 128 gray_file = os.path.join(output_gray_dir, filename.replace(".xml", ".png")) cv2.imwrite(gray_file, gray) ``` 其中,input_voc_dir是存放VOC格式标注文件的目录路径,output_gray_dir是输出灰度png图像的目录路径。 该代码会遍历目录下所有的xml文件(即VOC格式标注文件),根据标注信息生成相应的灰度的png图像,并存放在输出目录下。其中,目标区域的像素值为255,非目标区域的像素值为128。 执行完毕后,会在输出目录下生成与VOC格式标注文件对应的灰度png图像

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值