Anaconda安装及使用labelme制作实例分割自建数据集

这篇具有很好参考价值的文章主要介绍了Anaconda安装及使用labelme制作实例分割自建数据集。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.先创建 anaconda 虚拟环境 labelme,对应更改自己的python版本,我的是3.6.

①在Anaconda Prompt(虚拟环境对应的命令窗)中创建新的虚拟环境,命令如下:

conda create -n labelme python=3.6

②创建完成后,激活虚拟环境

conda activate labelme

③安装labelme 正常运转需要各种依赖的包,先下载pyqt和pillow

conda install pyqt
conda install pillow

均yes操作

④安装labelme

pip install labelme

至此,使用labelme的前期工作已经做完,接下来开始labelme的使用。

2.labelme的使用,进入桌面的anaconda prompt(假设你已经安装好了anaconda),激活labelme环境(在环境中,无需再次进入).

进入环境

activate labelme

打开labelme

labelme

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

3.打开labelme界面后,开始创作自己的数据集(可以是目标检测,也可以是实例分割,按照自己需求来) 

如下图所示,是labelme的界面

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 Open是打开某一张图片,Open Dir是打开存放你要打标的图片文件夹。
然后点击左侧Create Polygans,开始标点把目标圈起来。如下图所示。

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 圈起来之后,围成一个圈命名该标签为你的类名。例如下图中,红色命名为Belt,绿色命名为Shadow。

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 然后点击save保存,切换下一张图片继续打标,直至全部图片打标完成。

 到保存的路径,里面包含原图和json文件,如下图.

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 4.数据集转换前的准备

在你的instance_segmentation目录下包含4个文件,data_annotated里面存放你的原图和对应的json文件,labelme2coco.py是转为coco数据集的代码,labelme2voc.py是转为voc数据集的代码,labels.txt前两行不变,往下每一行写上你打标的类别,如下图所示。

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

在此,如果自己没有labelme转换函数,请将下列代码写成对应名称的.py文件

labelme2coco.py

#!/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()

 labelme2voc.py

#!/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()

5.voc数据集的转换

在你包含data_annotatedlabelme2coco.pylabelme2voc.pylabels.txt四个文件的文件夹根目录下,执行以下命令:

python labelme2voc.py data_annotated data_dataset_voc --labels labels.txt

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习运行结果如下,转换成功。

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

6.coco数据集的转换 

在你包含data_annotatedlabelme2coco.pylabelme2voc.pylabels.txt四个文件的文件夹根目录下,执行以下命令:

python labelme2coco.py data_annotated data_dataset_coco --labels labels.txt 

运行结果如下,转换成功。

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 7.转换完成

到你存放数据集的位置,已经生成data_dataset_coco和data_dataset_voc文件,就是对应的coco和voc数据集。

labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 以下为转换后的实例分割效果图labelme 实例分割,python,linux,ubuntu,人工智能,深度学习

 文章来源地址https://www.toymoban.com/news/detail-695926.html

到了这里,关于Anaconda安装及使用labelme制作实例分割自建数据集的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Python和OpenCV批量可视化labelme分割标注结果

    【原创声明】 本文为博主原创文章,未经博主允许不得转载。 更多算法总结请关注我的博客:https://blog.csdn.net/suiyingy。         在计算机视觉领域中,图像分割是一项重要的任务,它可以将图像中的不同物体或区域进行像素级别的分割。而在图像分割任务中,人工标注数

    2024年04月16日
    浏览(23)
  • labelme制作yolov5模型的数据集

    labelme制作yolov5模型的数据集,超级详细,主要步骤: labelme安装和使用教程 python实现json文件转txt文件格式 python实现对指定格式文件进行提取 找一批牛和马的数据集,用来做YOLOv5实现牛马检测识别任务,数据集格式如下: 1、安装labelme环境和labelme标注教程 (1)进入pycharm在

    2024年02月15日
    浏览(87)
  • ubuntu20.04系统安装使用labelme标注数据集

    请参考:Mediapipe+VSCode+Anaconda 实时检测手部关键点并保存视频_苦瓜汤补钙的博客-CSDN博客 1.打开终端创建虚拟环境   输入“y”,然后回车。  2.激活虚拟环境,开始安装  1、启动 2、点击【open】,选择图片;【Edit Polygons】---- 【Create Polygons】  3、可以选择自动保存  

    2024年02月16日
    浏览(32)
  • 深度学习:使用UNet做图像语义分割,训练自己制作的数据集,详细教程

    语义分割(Semantic Segmentation)是图像处理和机器视觉一个重要分支。与分类任务不同,语义分割需要判断图像每个像素点的类别,进行精确分割。语义分割目前在自动驾驶、自动抠图、医疗影像等领域有着比较广泛的应用。我总结了使用UNet网络做图像语义分割的方法,教程很详

    2024年02月03日
    浏览(36)
  • labelme的安装及使用

    步骤1:访问Anaconda官网,点击Download,下载Anaconda软件安装包。 步骤2:双击刚下载好的anaconda软件安装包,按照提示进行下一步操作即可。 步骤1:打开Anaconda Prompt,然后执行下面的命令,创建 labelme虚拟环境 步骤2:输入下面的命令,检查labelme是否下载成功,如果有如下图所

    2024年02月10日
    浏览(24)
  • 深度学习:使用UNet做图像语义分割,训练自己制作的数据集并推理测试(详细图文教程)

    语义分割(Semantic Segmentation)是图像处理和机器视觉一个重要分支。与分类任务不同,语义分割需要判断图像每个像素点的类别,进行精确分割。语义分割目前在自动驾驶、自动抠图、医疗影像等领域有着比较广泛的应用。我总结了使用UNet网络做图像语义分割的方法,教程很详

    2024年01月18日
    浏览(35)
  • 【技能---labelme软件的安装及其使用--ubuntu】

    图像检测需要自己的数据集,为此需要对一些数据进行数据标注,这里提供了一种图像的常用标注工具——labelme。 下面对其进行有一些介绍: Labelme 是一个图形界面的图像标注软件。其的设计灵感来自于 http://labelme.csail.mit.edu/ 。它是用 Python 语言编写的,图形界面使用的是

    2024年01月25日
    浏览(28)
  • labelImg和labelme的区别、安装和基本使用

    labelimg是一种矩形标注工具,常用于目标识别和目标检测,其标记数据输出为.xml和.txt labelme是一种多边形标注工具,可以准确的将轮廓标注出来,常用于分割,其标记输出格式为json labelImg和labelme都是训练数据集时,用于给数据集打标签的软件,但一个是矩形框,一个是可以

    2024年02月06日
    浏览(28)
  • Labelme使用——数据集标注详解

     1、Labelme的安装: Windows下首先安装Anaconda,安装教程:Windows下Anaconda的下载与安装_一诺长安的博客-CSDN博客 安装成功后,电计电脑左下角“开始”,找到Anaconda3(64-bit )下的Anaconda Prompt,并打开。  查看python版本:输入python或者python -V  创建虚拟环境:conda create -n labelm

    2024年02月08日
    浏览(29)
  • Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集

    由于本人水平有限,难免出现错漏,敬请批评改正。 更多精彩内容,可点击进入YOLO系列专栏或我的个人主页查看 YOLOv5:添加SE、CBAM、CoordAtt、ECA注意力机制 YOLOv5:yolov5s.yaml配置文件解读、增加小目标检测层 YOLOv5:IoU、GIoU、DIoU、CIoU、EIoU YOLOv7训练自己的数据集(口罩检测)

    2024年02月15日
    浏览(23)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包