Labelme 目标检测和语义分割的数据标注

2023-11-02

1.安装labelme

打开conda prompt 输入以下代码创建虚拟环境,打开虚拟环境,安装lelme。

conda create -n labelme python=3.6 //创建虚拟环境

conda activate labelme //打开虚拟环境

pip install labelme  //安装labelme

2.标注数据

安装labelme后再环境下输入labelme,回车打开labelme如图

 选择opendir打开要标注文件所在的文件夹,开始进行标注。在图片区域点击右键,如下图,如果是目标检测的话就点击Create Rectangle标注目标所在的目标框,若果是分割的话就点击Create Polygons。标注完成以后加上标签,别忘了保存。

 3.数据转换

在进行目标训练的时候经常要把标注的结果转化为需要的yolo格式,下面贴出数据集转yolo的代码。

## python  数据集转yolo代码
import json
import os

import cv2

file_dir = "E:/BaiduNetdiskDownload/all_images/all_images/"


files = [i for i in os.listdir(file_dir)]



label_list = []
for file in files:
    if not os.path.basename(file).endswith(".json"):
        continue
    file_path = os.path.join(file_dir, os.path.basename(file))
    image_path = file_path.replace(".json", ".bmp")
    print(image_path)
    image = cv2.imread(image_path)
    W = image.shape[1]
    H = image.shape[0]
    with open(file_path, "rb") as rf:
        file_in = json.load(rf)
    shapes = file_in["shapes"]
    anno = ""
    for shape in shapes:
        if shape["label"] not in label_list:
            label_list.append(shape["label"])
        x1 = shape["points"][0][0]
        y1 = shape["points"][0][1]
        x2 = shape["points"][1][0]
        y2 = shape["points"][1][1]
        x = (x1 + x2) / 2 / W
        y = (y1 + y2) / 2 / H
        w = (x2 - x1) / W
        h = (y2 - y1) / H

        anno += str(label_list.index(shape["label"])) + " " + str(x) + " " + str(y) + " " + str(w) + " " + str(h) + "\n"

    new_path = os.path.join(file_dir, os.path.basename(file).replace(".json", ".txt"))
    with open(new_path, "wb") as wf:
        wf.write(anno.encode())





## python 数据集 转yolo-face的代码

import json
import os

import cv2

file_dir = "E:/BaiduNetdiskDownload/yolo-face/new_dataset/images"

files = [i for i in os.listdir(file_dir)]

label_list = []
for file in files:
    if not os.path.basename(file).endswith(".json"):
        continue
    file_path = os.path.join(file_dir, os.path.basename(file))
    image_path = file_path.replace(".json", ".bmp")
    print(image_path)
    # image = cv2.imread(image_path)
    # W = image.shape[1]
    # H = image.shape[0]
    with open(file_path, "rb") as rf:
        file_in = json.load(rf)
    shapes = file_in["shapes"]
    W = file_in["imageWidth"]
    H = file_in["imageHeight"]
    anno = ""
    for shape in shapes:
        if shape["label"] == "target":
            x1 = shape["points"][0][0]
            y1 = shape["points"][0][1]
            x2 = shape["points"][1][0]
            y2 = shape["points"][1][1]
            x = (x1 + x2) / 2 / W
            y = (y1 + y2) / 2 / H
            w = (x2 - x1) / W
            h = (y2 - y1) / H
        if shape["label"] == "circle_point":
            x3 = shape["points"][0][0] / W
            y3 = shape["points"][0][1] / H
            x4 = shape["points"][1][0] / W
            y4 = shape["points"][1][1] / H

            x5 = (x3 + x4) / 2
            y5 = (y3 + y4) / 2
            p1 = (x3, y5)  # left
            p2 = (x5, y3)  # top
            p3 = (x4, y5)  # right
            p4 = (x5, y4)  # bottom
            p5 = (x5, y5)  # center

    print(x1)
    anno = "0" + " " + str(x) + " " + str(y) + " " + str(w) + " " + str(h) + " " + str(x3) + " " + str(y5) + " " + str(x5) + " " + str(y3) + " " + str(x4) + " " + str(y5) + " " + str(x5) + " " + str(y4) + " " + str(x5) + " " + str(y5) + "\n"

    new_path = os.path.join(file_dir, os.path.basename(file).replace(".json", ".txt"))
    with open(new_path, "wb") as wf:
        wf.write(anno.encode())

下面语义分割数据集转化

# 1.单张图片的转化

# cd 到标注的文件夹执行以下命令

labelme_json_to_dataset x.json -o x

#  x.json 要转化的数据
#  x  要输出的目录文件夹

多张图片的转化如下:

首先准备好自己的txt文件,文件中设置好自己的标签。

__ignore__
_background_
human
bike
bottle
//执行以下代码

python labelme2voc.py  input_dir output_dir  --lables  labels.txt


iput_dir 标注文件所在文件夹

output_dir 输出结果的文件夹

labels.txt  指定标签文件的文件名,可更改

下面是lableme2voc.py代码,不方便下载的可以自己从下面拷贝代码,也可以自己下载源文件

#label_to_voc文件内容

#!/usr/bin/env python

from __future__ import print_function

import argparse
import glob
import os
import os.path as osp
import sys

import imgviz
import numpy as np

import labelme


def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("input_dir", help="input annotated directory")
    parser.add_argument("output_dir", help="output dataset directory")
    parser.add_argument("--labels", help="labels file", required=True)
    parser.add_argument(
        "--noviz", help="no visualization", action="store_true"
    )
    args = parser.parse_args()

    if osp.exists(args.output_dir):
        print("Output directory already exists:", args.output_dir)
        sys.exit(1)
    os.makedirs(args.output_dir)
    os.makedirs(osp.join(args.output_dir, "JPEGImages"))
    os.makedirs(osp.join(args.output_dir, "SegmentationClass"))
    os.makedirs(osp.join(args.output_dir, "SegmentationClassPNG"))
    if not args.noviz:
        os.makedirs(
            osp.join(args.output_dir, "SegmentationClassVisualization")
        )
    os.makedirs(osp.join(args.output_dir, "SegmentationObject"))
    os.makedirs(osp.join(args.output_dir, "SegmentationObjectPNG"))
    if not args.noviz:
        os.makedirs(
            osp.join(args.output_dir, "SegmentationObjectVisualization")
        )
    print("Creating dataset:", args.output_dir)

    class_names = []
    class_name_to_id = {}
    for i, line in enumerate(open(args.labels).readlines()):
        class_id = i - 1  # starts with -1
        class_name = line.strip()
        class_name_to_id[class_name] = class_id
        if class_id == -1:
            assert class_name == "__ignore__"
            continue
        elif class_id == 0:
            assert class_name == "_background_"
        class_names.append(class_name)
    class_names = tuple(class_names)
    print("class_names:", class_names)
    out_class_names_file = osp.join(args.output_dir, "class_names.txt")
    with open(out_class_names_file, "w") as f:
        f.writelines("\n".join(class_names))
    print("Saved class_names:", out_class_names_file)

    for filename in glob.glob(osp.join(args.input_dir, "*.json")):
        print("Generating dataset from:", filename)

        label_file = labelme.LabelFile(filename=filename)

        base = osp.splitext(osp.basename(filename))[0]
        out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")
        out_cls_file = osp.join(
            args.output_dir, "SegmentationClass", base + ".npy"
        )
        out_clsp_file = osp.join(
            args.output_dir, "SegmentationClassPNG", base + ".png"
        )
        if not args.noviz:
            out_clsv_file = osp.join(
                args.output_dir,
                "SegmentationClassVisualization",
                base + ".jpg",
            )
        out_ins_file = osp.join(
            args.output_dir, "SegmentationObject", base + ".npy"
        )
        out_insp_file = osp.join(
            args.output_dir, "SegmentationObjectPNG", base + ".png"
        )
        if not args.noviz:
            out_insv_file = osp.join(
                args.output_dir,
                "SegmentationObjectVisualization",
                base + ".jpg",
            )

        img = labelme.utils.img_data_to_arr(label_file.imageData)
        imgviz.io.imsave(out_img_file, img)

        cls, ins = labelme.utils.shapes_to_label(
            img_shape=img.shape,
            shapes=label_file.shapes,
            label_name_to_value=class_name_to_id,
        )
        ins[cls == -1] = 0  # ignore it.

        # class label
        labelme.utils.lblsave(out_clsp_file, cls)
        np.save(out_cls_file, cls)
        if not args.noviz:
            clsv = imgviz.label2rgb(
                cls,
                imgviz.rgb2gray(img),
                label_names=class_names,
                font_size=15,
                loc="rb",
            )
            imgviz.io.imsave(out_clsv_file, clsv)

        # instance label
        labelme.utils.lblsave(out_insp_file, ins)
        np.save(out_ins_file, ins)
        if not args.noviz:
            instance_ids = np.unique(ins)
            instance_names = [str(i) for i in range(max(instance_ids) + 1)]
            insv = imgviz.label2rgb(
                ins,
                imgviz.rgb2gray(img),
                label_names=instance_names,
                font_size=15,
                loc="rb",
            )
            imgviz.io.imsave(out_insv_file, insv)


if __name__ == "__main__":
    main()

下面是voc2coco代码:

#!/usr/bin/env python

import argparse
import collections
import datetime
import glob
import json
import os
import os.path as osp
import sys
import uuid

import imgviz
import numpy as np

import labelme

try:
    import pycocotools.mask
except ImportError:
    print("Please install pycocotools:\n\n    pip install pycocotools\n")
    sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("input_dir", help="input annotated directory")
    parser.add_argument("output_dir", help="output dataset directory")
    parser.add_argument("--labels", help="labels file", required=True)
    parser.add_argument(
        "--noviz", help="no visualization", action="store_true"
    )
    args = parser.parse_args()

    if osp.exists(args.output_dir):
        print("Output directory already exists:", args.output_dir)
        sys.exit(1)
    os.makedirs(args.output_dir)
    os.makedirs(osp.join(args.output_dir, "JPEGImages"))
    if not args.noviz:
        os.makedirs(osp.join(args.output_dir, "Visualization"))
    print("Creating dataset:", args.output_dir)

    now = datetime.datetime.now()

    data = dict(
        info=dict(
            description=None,
            url=None,
            version=None,
            year=now.year,
            contributor=None,
            date_created=now.strftime("%Y-%m-%d %H:%M:%S.%f"),
        ),
        licenses=[
            dict(
                url=None,
                id=0,
                name=None,
            )
        ],
        images=[
            # license, url, file_name, height, width, date_captured, id
        ],
        type="instances",
        annotations=[
            # segmentation, area, iscrowd, image_id, bbox, category_id, id
        ],
        categories=[
            # supercategory, id, name
        ],
    )

    class_name_to_id = {}
    for i, line in enumerate(open(args.labels).readlines()):
        class_id = i - 1  # starts with -1
        class_name = line.strip()
        if class_id == -1:
            assert class_name == "__ignore__"
            continue
        class_name_to_id[class_name] = class_id
        data["categories"].append(
            dict(
                supercategory=None,
                id=class_id,
                name=class_name,
            )
        )

    out_ann_file = osp.join(args.output_dir, "annotations.json")
    label_files = glob.glob(osp.join(args.input_dir, "*.json"))
    for image_id, filename in enumerate(label_files):
        print("Generating dataset from:", filename)

        label_file = labelme.LabelFile(filename=filename)

        base = osp.splitext(osp.basename(filename))[0]
        out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")

        img = labelme.utils.img_data_to_arr(label_file.imageData)
        imgviz.io.imsave(out_img_file, img)
        data["images"].append(
            dict(
                license=0,
                url=None,
                file_name=osp.relpath(out_img_file, osp.dirname(out_ann_file)),
                height=img.shape[0],
                width=img.shape[1],
                date_captured=None,
                id=image_id,
            )
        )

        masks = {}  # for area
        segmentations = collections.defaultdict(list)  # for segmentation
        for shape in label_file.shapes:
            points = shape["points"]
            label = shape["label"]
            group_id = shape.get("group_id")
            shape_type = shape.get("shape_type", "polygon")
            mask = labelme.utils.shape_to_mask(
                img.shape[:2], points, shape_type
            )

            if group_id is None:
                group_id = uuid.uuid1()

            instance = (label, group_id)

            if instance in masks:
                masks[instance] = masks[instance] | mask
            else:
                masks[instance] = mask

            if shape_type == "rectangle":
                (x1, y1), (x2, y2) = points
                x1, x2 = sorted([x1, x2])
                y1, y2 = sorted([y1, y2])
                points = [x1, y1, x2, y1, x2, y2, x1, y2]
            if shape_type == "circle":
                (x1, y1), (x2, y2) = points
                r = np.linalg.norm([x2 - x1, y2 - y1])
                # r(1-cos(a/2))<x, a=2*pi/N => N>pi/arccos(1-x/r)
                # x: tolerance of the gap between the arc and the line segment
                n_points_circle = max(int(np.pi / np.arccos(1 - 1 / r)), 12)
                i = np.arange(n_points_circle)
                x = x1 + r * np.sin(2 * np.pi / n_points_circle * i)
                y = y1 + r * np.cos(2 * np.pi / n_points_circle * i)
                points = np.stack((x, y), axis=1).flatten().tolist()
            else:
                points = np.asarray(points).flatten().tolist()

            segmentations[instance].append(points)
        segmentations = dict(segmentations)

        for instance, mask in masks.items():
            cls_name, group_id = instance
            if cls_name not in class_name_to_id:
                continue
            cls_id = class_name_to_id[cls_name]

            mask = np.asfortranarray(mask.astype(np.uint8))
            mask = pycocotools.mask.encode(mask)
            area = float(pycocotools.mask.area(mask))
            bbox = pycocotools.mask.toBbox(mask).flatten().tolist()

            data["annotations"].append(
                dict(
                    id=len(data["annotations"]),
                    image_id=image_id,
                    category_id=cls_id,
                    segmentation=segmentations[instance],
                    area=area,
                    bbox=bbox,
                    iscrowd=0,
                )
            )

        if not args.noviz:
            viz = img
            if masks:
                labels, captions, masks = zip(
                    *[
                        (class_name_to_id[cnm], cnm, msk)
                        for (cnm, gid), msk in masks.items()
                        if cnm in class_name_to_id
                    ]
                )
                viz = imgviz.instances2rgb(
                    image=img,
                    labels=labels,
                    masks=masks,
                    captions=captions,
                    font_size=15,
                    line_width=2,
                )
            out_viz_file = osp.join(
                args.output_dir, "Visualization", base + ".jpg"
            )
            imgviz.io.imsave(out_viz_file, viz)

    with open(out_ann_file, "w") as f:
        json.dump(data, f)


if __name__ == "__main__":
    main()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Labelme 目标检测和语义分割的数据标注 的相关文章

随机推荐

  • Sonar代码扫描常见规则总结

    Sonar代码扫描常见规则 最近公司项目交付 交付前集成 功能 性能 安全种种测试工作就来了 由于测试离职 被抓壮丁 兼职起测试修改工作 小公司 平时敲 ctrl c 代码 ctrl v 时 同事也不在意一些代码规范 以及一些常见的规约要求
  • 为啥海康摄像头网页无法预览

    最近在做IPC相关的业务 用谷歌 火狐都无法预览摄像头画面 即使装了插件也不行 后面发现了 要用IE打开 才能预览 转载于 https www cnblogs com 132818Creator p 10980880 html
  • python 面向对象编程(2)

    文章目录 前言 封装 多态 类属性和实例属性 定义以及访问类属性 修改类属性 实例属性 类方法 静态方法 前言 前面我们介绍了 python 类和对象以及继承 私有权限 那么今天我们将来介绍 python面向对象 剩下的两大特性封装 多态
  • 蓝桥杯Python->面向对象:类 and 方法 练习->成绩分析练习

    作者 芝士小熊饼干 系列专栏 数据结构 蓝桥杯 算法 坚持天数 3天 烤地瓜案例练习实现对面向对象的理解 抽象一个地瓜类 class SweetPotato object 实现初始化方法 初始地瓜的状态和总烧烤时间 def init sel
  • scala运行异常Could not locate executable null\bin\winutils.exe in the Hadoop binaries

    java io IOException Could not locate executable null bin winutils exe in the Hadoop binaries 出现这个问题的原因是我们在windows上模拟开发环境
  • 使用vuex实时更新右上角通知信息的红点数量

    需求如图 因为这两个不存在组件关系 所以我们使用Vuex来解决这个实时刷新 1 首先在vuex的state定义数据如下 state noticeCount 0 2 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
  • ensp usg6000v ping不通_华为USG6000V防火墙和VMWARE的联动

    快到周末了 来一篇技术类公众号文章 最近看一本很有意思的书 叫 华为防火墙技术漫谈 俗话说得好 理论结合实践才是王道 下面来简要描述一下本周做过的一个比较有意思的实验 在这个实验中使用到了ENSP模拟器 USG6000V防火墙 VMWARE
  • 【数模研赛】“华为杯”第十九届中国研究生数学建模竞赛C题分享——(四)问题二模型建立

    写在前面 第十九届数模研赛在22年10月6 10日开展 我和我的两名队友肝了5天 整出来一篇论文 因为不确定自己做的好不好 所以一直没写博客 前两天结果出来了 我们队拿了国二 在C题里排名88 1134 感觉结果还不错 以后应该也不会再有机
  • UE4 实现控制场景中所有物体透明度功能

    本文会讲解如何利用材质参数集简单的实现修改场景中所有物体透明度的功能 讲解地图为第三人称地图 1 创建材质变量集 这里面新建的变量可以在蓝图中控制 这样就能很方便的修改透明度 因为透明度是只有一个值的参数所以创建scalar参数 默认值为1
  • c语言的product,张永强:C语言中product是什么意思

    吴俊光的回答 product在C语言中不是关键字 C库中也没有这样的函数名 所以pruduct有两种可能 1是编程者自己定义的变量 2是编程者自定义的函数的名字 这里product是自定义函数的名字 功能就是返回a乘b的结果 实现一个乘法功
  • 【转载】Linux下用ls和du命令查看文件以及文件夹大小

    1 ls的用法 ls ll 列出当前目录下所有文件的大小以及所有文件大小的统计总和 显示成字节大小 ls lh 列出当前目录下所有文件的大小以及所有文件大小的统计总和 以KB MB等为单位进行显示 ls l grep wc l 或 find
  • 基于BCM53262交换芯片平台的Linux操作系统移植(四)之代码调试与驱动书写

    2018 05 09 10 49 zhoulinhua 2018 05 10 一 系统分区 name address size bootstrap 0x0 64k u boot 0x10000 640k env 0xb0000 192k d
  • 【C语言】练习题 - 菲姐游泳 - 附视频讲解

    游泳奥运冠军菲姐刻苦训练 从早上a时b分开始下水训练 直到当天的c时d分结束 请编程计算 菲姐当天一共训练多少小时多少分钟 本文引用自作者编写的下述图书 本文允许以个人学习 教学等目的引用 讲授或转载 但需要注明原作者 海洋饼干叔 叔 本文
  • 独立按键消抖与松手检测

    记录下最近独立按键消抖和松手检测 我对独立按键的处理思路是 1 获得键值 2 消抖处理 3 松手检测 4 键值解析 1 获得键值 这里把独立按键做个编号 例如有两个按键记为KEY0 KEY1 用一个变量来记录当前按键标记值 比如Cur Ke
  • npm install 编译时报“Cannot read properties of null (reading ‘pickAlgorithm‘)“

    先看报错 先说下网上大多数的解决方案 方案一 重新安装node解决 方案二 删了node models重新下 或者直接下载CNPM 淘宝镜像 进行安装 CNPM安装办法 npm install g cnpm registry https r
  • 解决STM32驱动0.96OLED不亮的问题

    问题描述 使用STM32无法驱动OLED 解决方案 1 检查硬件连接是否有误 OLED STM32 VCC 5V或3 3V SDA SDA SCL SCL GND GND 备注 最好接STM32最小系统版的3 3V 当连接STM32最小系统
  • Javaio流

    io流 关于Java的io流一般按照数据操作类型可以分为字节流与字符流 首先来说一下字节流 字节流 字节流的方法都是以stream结尾的 字节流的用途 转换图片为二进制 转换音频 视屏为二进制 字符串等也可以转为二进制 字节流常用于图片 音
  • 签到题【牛客算法周周练6E】【暴力枚举+线段树】

    题目链接 题目保证数据随机 数据随机真的是太强了 直接可以跑最坏时候是的复杂度 直接暴力建线段树 然后更新的时候更新到底 查询的时候也是查询到底 因为数据随机 所以其实被处理的次数是很少的 因为要刚好是set里有的 或者是set里没有的 这
  • Unity3D-----三维数学(向量)

    Unity3d gt 三维数学之向量 一 向量 1 什么是向量 2 向量的形式 3 向量的大小 4 向量的方向 二 向量运算 1 向量相减 2 向量相加 3 向量与标量的乘除法 4 点乘 5 叉乘 三 三角函数 1 角的度量单位 2 三角函
  • Labelme 目标检测和语义分割的数据标注

    1 安装labelme 打开conda prompt 输入以下代码创建虚拟环境 打开虚拟环境 安装lelme conda create n labelme python 3 6 创建虚拟环境 conda activate labelme 打