栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

可视化COCO分割标注文件,以及单个json合成coco格式标注文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

可视化COCO分割标注文件,以及单个json合成coco格式标注文件

 可视化coco分割标注

import cv2
import random
import json, os
from pycocotools.coco import COCO
from skimage import io
from matplotlib import pyplot as plt


coco_classes = ["111", "112", "113", "121", "122", "123", "131", "132", "133",
                "211", "212", "213", "221", "222", "223", "231", "232", "233",
                "311", "312", "313", "321", "322", "323", "331", "332", "333",
                "411", "412", "413", "421", "422", "423", "431", "432", "433",
                "511", "512", "513", "521", "522", "523", "531", "532", "533",
                "611", "612", "613", "621", "622", "623", "631", "632", "633",
                "711", "712", "713", "721", "722", "723", "731", "732", "733"]


def visualization_bbox_seg(json_path, img_path, *str):   # 需要画图的是第num副图片, 对应的json路径和图片路径

    coco = COCO(json_path)

    if len(str) == 0:
        catIds = []
    else:
        catIds = coco.getCatIds(catNms = [str[0]])      # 获取给定类别对应的id 的dict(单个内嵌字典的类别[{}])
        catIds = coco.loadCats(catIds)[0]['id']         # 获取给定类别对应的id 的dict中的具体id

    list_imgIds = coco.getImgIds(catIds=catIds )        # 获取含有该给定类别的所有图片的id
    # print(list_imgIds)

    for idx in range(len(list_imgIds)):
        img = coco.loadImgs(list_imgIds[idx])[0]    # 获取满足上述要求,并给定显示第num幅image对应的dict
        # print(img)
        # # {'license': 1, 'file_name': 'joint_5502.jpg', 'clothes_url': 'None', 'height': 1080, 'width': 1920, 'date_captured': '1998-02-05 05:02:01', 'flickr_url': 'None', 'id': 1}

        image = io.imread(os.path.join(img_path, img['file_name']))     # 读取图像
        image_name =  img['file_name']                      # 读取图像名字
        image_id = img['id']                                # 读取图像id

        img_annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) # 读取这张图片的所有seg_id
        # print(img_annIds)
        # # [1, 2, 3]

        img_anns = coco.loadAnns(img_annIds)
        # print(img_anns)

        for i in range(len(img_annIds)):
            x, y, w, h = img_anns[i-1]['bbox']          # 读取边框
            name = coco_classes[img_anns[i-1]['category_id']]
            image = cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 255), 1)      # 绘制矩形框
            cv2.putText(image, name, (int(x+w/2), int(y+h/2)), 5, 3, (255, 0, 0), 3)                           # 绘制标签
            # 各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细

        print(f"{img['file_name']} find {len(img_annIds)} objects")

        plt.rcParams['figure.figsize'] = (16.0, 8.5)
        plt.imshow(image)
        coco.showAnns(img_anns)
        plt.show()

        # break

if __name__ == "__main__":
    train_json = './clothes_val_COCO.json'
    train_path = 'hx_clothes_1122/total_val'
    visualization_bbox_seg(train_json, train_path)      # 最后一个参数不写就是画出一张图中的所有类别

单个json文件合成coco格式大json文件

import sys
import os
import json
from PIL import Image
from tqdm import tqdm
from itertools import chain


START_BOUNDING_BOX_ID = 721           # testing need to change 701   235 721

# If necessary, pre-define category and its id
'''
material:
    1、化纤 Chemical-fiber,
    2、棉麻 Cotton-linen,
    3、羊毛 wool,
    4、皮革 leather,
    5、皮草 fur,
    6、牛仔 jeans,
    7、丝质 silk;

color:
    1、深色 deep-color,
    2、浅色 light-color,
    3、白色 white;

style:
    1、上衣 jacket,
    2、裤子 pants,
    3、内衣 underwear
'''
PRE_DEFINE_CATEGORIES = {"111": 1, "112": 2, "113": 3, "121": 4, "122": 5, "123": 6, "131": 7, "132": 8, "133": 9, "211": 10, "212": 11, "213": 12, "221": 13, "222": 14, "223": 15, "231": 16, "232": 17, "233": 18, "311": 19, "312": 20, "313": 21, "321": 22, "322": 23, "323": 24, "331": 25, "332": 26, "333": 27, "411": 28, "412": 29, "413": 30, "421": 31, "422": 32, "423": 33, "431": 34, "432": 35, "433": 36, "511": 37, "512": 38, "513": 39, "521": 40, "522": 41, "523": 42, "531": 43, "532": 44, "533": 45, "611": 46, "612": 47, "613": 48, "621": 49, "622": 50, "623": 51, "631": 52, "632": 53, "633": 54, "711": 55, "712": 56, "713": 57, "721": 58, "722": 59, "723": 60, "731": 61, "732": 62, "733": 63}

# 50000 110971

def convert(jsonsFile, json_file, imgPath):


	# ########################################### define the head #################################################
    imgs = os.listdir(imgPath)
    json_dict = {"info":{}, "licenses":[], "images":[], "annotations": [], "categories": []}


	# ######################################### info, type is dict ################################################
    info = {'description': 'Clothes Dataset', 'url': 'None', 'version': '1.0', 'year': 2021, 'contributor': 'Donghao Zhangdi etc', 'note': 'material: Chemical-fiber,Cotton-linen,wool,leather,Fur,jeans,silk; color: deep-color,light-color,white; style: jacket,pants,underwear. total 63(7x3x3) categories', 'date_created': '2021/11/25'}
    json_dict['info'] = info


	# ####################################### licenses, type is list ##############################################
    license = {'url': 'None', 'id': 1, 'name': 'None'}
    json_dict['licenses'].append(license)


	# ###################################### categories, type is list #############################################
    categories = PRE_DEFINE_CATEGORIES
    for cate, cid in categories.items():
        cat = {'supercategory': 'none', 'id': cid , 'name': cate} # no + 1
        json_dict['categories'].append(cat)


    bnd_id = START_BOUNDING_BOX_ID
    jsonnamelist = os.listdir(jsonsFile)
    jsonnamelist = [item for item in jsonnamelist if item[-4:] == 'json']
    for idx, jsonname in enumerate(tqdm(jsonnamelist)):

		# ###################################### images, type is list #############################################
        image_id = idx + 236
        image_name = jsonname.replace(".json", ".jpg")
        if image_name not in imgs:
            with open('./error.txt', 'a') as target:
                info = f'No image file in image path:n{jsonname} ==> {image_name}nn'
                target.write(info)
            continue
        img = Image.open(os.path.join(imgPath, image_name))
        width, height = img.size

        image = {'license': 1, 'file_name': image_name, 'clothes_url': 'None', 'height': height, 'width': width, 'date_captured': '1998-02-05 05:02:01', 'flickr_url': 'None', 'id': image_id}
        json_dict['images'].append(image)


        # ###################################### annotations, type is list #############################################
        json_path = os.path.join(jsonsFile, jsonname)
        with open(json_path, 'r') as load_f:
            load_dict = json.load(load_f)

        for obj in load_dict:

            label = obj['name']
            if label not in categories.keys():
                new_id = len(categories)
                categories[label] = new_id+1
            category_id = categories[label]

            points = obj['points']
            pointsList = list(chain.from_iterable(points))
            pointsList = [float(p) for p in pointsList] ####### point 必须是浮点数!!!!!!!!!!!!!!

            seg = [pointsList]

            row = pointsList[0::2]
            clu = pointsList[1::2]
            left_top_x = min(row)
            left_top_y = min(clu)
            right_bottom_x = max(row)
            right_bottom_y = max(clu)
            wd = right_bottom_x - left_top_x
            hg = right_bottom_y - left_top_y

            ann = {'segmentation': seg, 'area': wd*hg, 'iscrowd': 0, 'image_id': image_id, 'bbox': [left_top_x, left_top_y, wd, hg], 'category_id': category_id, 'id': bnd_id}
            json_dict['annotations'].append(ann)
            bnd_id = bnd_id + 1
    print(image_id, bnd_id)

	# ######################################### write into local ################################################
    with open(json_file, 'w') as json_fp:
        json.dump(json_dict, json_fp)


if __name__ == '__main__':
    # jsonsFile = "hx_clothes_1122/hx_clothes_masks"
    # imgPath = "hx_clothes_1122/hx_clothes_imgs"
    # destJson = "./clothes_train_COCO.json"
    jsonsFile = "hx_clothes_1122/total_train_jsons"
    imgPath = "hx_clothes_1122/total_train"
    destJson = "./clothes_train_COCO.json"
    # jsonsFile = "hx_clothes_1122/total_val_jsons"
    # imgPath = "hx_clothes_1122/total_val"
    # destJson = "./clothes_val_COCO.json"

    convert(jsonsFile, destJson, imgPath)

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648677.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号