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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • HDLBits答案(12)_Verilog移位寄存器「建议收藏」

    HDLBits答案(12)_Verilog移位寄存器「建议收藏」Verilog移位寄存器HDLBits链接前言今天更新一节寄存器相关内容,其中涉及CRC校验的内容是用线性反馈移位寄存器搭建而成的。题库题目描述1:构建一个4bit的移位寄存器(右移),含异步复位、同步加载和使能areset:让寄存器复位为0load:加载4bit数据到移位寄存器中,不移位ena:使能右移q:移位寄存器中的内容Solution1:moduletop_module(inputclk,inputareset,//asyncacti

    2022年7月16日
    15
  • mysql时序性数据库_时序数据库入门[通俗易懂]

    mysql时序性数据库_时序数据库入门[通俗易懂]数据库的模型包含关系型、key-value型、Document型等很多种,那么为什么新型的时序数据库成为监控数据存储的新宠呢?下面就会从为什么需要时序数据库?时序数据库的数据结构两个方面来介绍一下时序数据库。1.为什么需要时序数据库1.1时序数据特点时序数据有如下几个特点:基本上是插入操作较多且无更新的需求数据带有时间属性,且数据量随着时间递增插入数据多,每秒钟插入需要可到达千万甚至是上…

    2022年10月5日
    3
  • switch中的continue和break区别[通俗易懂]

    switch中的continue和break区别[通俗易懂]今天c程设期末考试,突然有一道选择题是关于switch中的break和continue问题。若switch外部没有循环,则break和continue没有区别。若switch外部还有循环,{一.若break,continue在switch外部,则二者作用的是外部循环。二.若break,continue在switch内部,则break作用于switch,continue作用于外部循环。…

    2025年11月5日
    2
  • Windows 定时执行脚本[通俗易懂]

    Windows 定时执行脚本[通俗易懂]Windows定时执行脚本1、参考资料windows设置定时执行脚本2、解决办法由于Windows系统,无法使用Linux下强大的crontab命令,所以该定时任务也是针对Windo系统的具体操作步骤右击【我的电脑】,选择【管理】在【任务计划程序】面板中点击【创建基本任务】输入任务的【名称】和【描述】当然是希望每天自动执行防疫打卡啦~设置每天执行任务的时间,以及每隔几天执行一次该任务选择【启动程序】选择启动程序的startup.bat

    2022年7月17日
    58
  • JSONObject与JSONArray的使用

    JSONObject与JSONArray的使用

    2021年11月15日
    40
  • emexecexe_alg是什么进程

    emexecexe_alg是什么进程 今天天气不错,早上做完志愿者时也比较顺利,特别是遇到了一些好牛X的老太太/老头,高兴。于是,啃完饭后就直奔B218,准备看看好久之前就说好要看的STL,可是…… 不一会儿就看烦了,玩了局句CS,接着就在那里无所事事的翻机房电脑(顺便说一下,我今天才发现,原理咱机房电脑是双核(pentium3G*2+1GDDR2,怪不得跑CS比我那神舟顺多了).翻着翻着,看见一个OS

    2022年10月3日
    3

发表回复

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

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