mask rcnn训练自己的数据集_fasterrcnn训练自己的数据集

mask rcnn训练自己的数据集_fasterrcnn训练自己的数据集这篇博客是基于GoogleColab的maskrcnn训练自己的数据集(以实例分割为例)文章中数据集的制作这部分的一些补充温馨提示:实例分割是针对同一个类别的不同个体或者不同部分之间进行区分我的任务是对同一个类别的不同个体进行区分,在标注的时候,不同的个体需要设置不同的标签名称在进行标注的时候不要勾选labelme界面左上角File下拉菜单中的StayWithImagesData选项否则生成的json会包含Imagedata信息(是很长的一大串加密的软链接

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

这篇博客是 基于 Google Colab 的 mask rcnn 训练自己的数据集(以实例分割为例)文章中 数据集的制作 这部分的一些补充

温馨提示:

实例分割是针对同一个类别的不同个体或者不同部分之间进行区分
我的任务是对同一个类别的不同个体进行区分,在标注的时候,不同的个体需要设置不同的标签名称

在进行标注的时候不要勾选 labelme 界面左上角 File 下拉菜单中的 Stay With Images Data 选项
否则生成的json会包含 Imagedata 信息(是很长的一大串加密的软链接),会占用很大的内存

在这里插入图片描述

1.首先要人为划分训练集和测试集(图片和标注文件放在同一个文件夹里面)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2.在同级目录下新建一个 labels.txt 文件

__ignore__
__background__
seedling #根据自己的实际情况更改

在这里插入图片描述
3.在datasets目录下新建 seed_trainseed_val 两个文件夹

分别存放的训练集和测试集图片和整合后的标签文件
seed_train 
seed_val

把整合后的标签文件剪切复制到同级目录下
seed_train_annotation.josn
seed_val_annotation.json

在这里插入图片描述

完整代码

说明:
一次只能操作一个文件夹,也就是说:
训练集生成需要执行一次代码
测试集生成就需要更改路径之后再执行一次代码
import argparse
import collections
import datetime
import glob
import json
import os
import os.path as osp
import sys
import uuid
import time

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)

#https://github.com/pascal1129/kaggle_airbus_ship_detection/blob/master/0_rle_to_coco/1_ships_to_coco.py

def main():
    parser = argparse.ArgumentParser(description="json2coco")
    #原始json文件保存的路径
    parser.add_argument("--input_dir", help="input annotated directory",default="E:/Deep_learning/seed-mask/data/seed/seed_train")
    #整合后的json文件保存的路径
    parser.add_argument("--output_dir", help="output dataset directory",default="E:/Deep_learning/seed-mask/data/seed/datasets/seed_train")
    parser.add_argument("--labels", help="labels file", default='E:/Deep_learning/seed-mask/data/seed/labels.txt')#required=True
    parser.add_argument( "--noviz", help="no visualization", action="store_true" ,default="--noviz")
    args = parser.parse_args()

    now = datetime.datetime.now()
    start= time.time()

    data = dict(
        info=dict(
            description="seedling datasets",
            url=None,
            version="label=4.5.6",
            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
        if class_id == 0:
            assert class_name == "__background__"
            continue        
        class_name_to_id[class_name] = class_id
        #print(class_id,class_name,'\n')
        data["categories"].append(
            dict(supercategory="seedling", id=class_id, name=class_name,)#一类目标+背景,id=0表示背景
        )
    print("categories 生成完成",'\n')

    out_ann_file = osp.join(args.output_dir, "seed_train_anno.json")#自动添加"/" 这里要改 
    
    
    label_files = glob.glob(osp.join(args.input_dir, "*.json"))#图像id从json文件中读取
    for image_id, filename in enumerate(label_files):
        print(image_id, filename)
        #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, 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.shape_to_mask(img.shape[:2], points, shape_type)#labelme=4.5.6的shape_to_mask函数
            if group_id is None:
                group_id = uuid.uuid1()

            instance = (label, group_id)
            #print(instance)

            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]
            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=1,#都是1类cls_id
                    segmentation=segmentations[instance],
                    area=area,
                    bbox=bbox,
                    iscrowd=0,
                )
            )
    
    print("annotations 生成完成",'\n')

# if not args.noviz:
# 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,indent = 2)
        
    cost_time =(time.time()-start)/1000
    print("cost_time:{:.2f}s".format(cost_time) )


if __name__ == "__main__":
    main()
    
    
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/172437.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Linux安装rinetd

    为什么80%的码农都做不了架构师?>>>…

    2022年4月7日
    120
  • fatal: unable to access https:// Failed to connect to: Connection refused|git clone问题(完美解决)

    fatal: unable to access https:// Failed to connect to: Connection refused|git clone问题(完美解决)fatal:unabletoaccess‘https://github.com/xxxx/’:Failedtoconnecttox.x.x.xportxxxxx:Connectionrefused|gitclone问题(完美解决)系统:ubuntu14.04问题描述执行以下命令克隆目标源码到本地时,会出现错误。gitclonehttps://gith…

    2022年6月21日
    59
  • leetcode-221. 最大正方形(动态规划)「建议收藏」

    leetcode-221. 最大正方形(动态规划)「建议收藏」在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。示例 1:输入:matrix = [[“1″,”0″,”1″,”0″,”0”],[“1″,”0″,”1″,”1″,”1”],[“1″,”1″,”1″,”1″,”1”],[“1″,”0″,”0″,”1″,”0”]]输出:4示例 2:输入:matrix = [[“0″,”1”],[“1″,”0”]]输出:1示例 3:输入:matrix = [[“0”]]输出:0 提示:m == ma

    2022年8月9日
    3
  • BLSP_用冰块和棉签玩哭凹凸世界

    BLSP_用冰块和棉签玩哭凹凸世界1.基础概念(1)   BusAccessModule(BAM),总线访问模块BAMisusedtomovedatato/fromtheperipheralbuffers.(2)   BAMLow-SpeedPeripheral(BLSP),低速接口的总线访问模块(3)   QUP:QualcommUniversalPeripheral,高通统一的…

    2022年10月19日
    0
  • 彻底禁止win10更新的锅「建议收藏」

    彻底禁止win10更新的锅「建议收藏」背景:tonight,和往常一样,就在打开vmware的一瞬间……突然弹出下面这个令人懵逼致死的图:百度搜索一通,众说纷纭,发现竟然还是win10系统的锅。下面开始解决问题,直接上图:这1903版本不支持vmware14,需要更新vm为15版本,商业套路,NM真够了,果断拒绝,还是另想办法吧;想着把1903更新卸载了,但是没有卵用,重启之后,出现下图,反应老半天…

    2022年6月17日
    20
  • QQ群关系数据库处理

    QQ群关系数据库处理1.附加数据库1EXECsp_attach_single_file_db@dbname='GroupData1_Data',@physname='/media/

    2022年7月3日
    26

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号