可视化COCO分割标注文件,以及单个json合成coco格式标注文件
生活随笔
收集整理的這篇文章主要介紹了
可视化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 pltcoco_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中的具體idlist_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'] # 讀取圖像idimg_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()# breakif __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 chainSTART_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 110971def 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_CATEGORIESfor cate, cid in categories.items():cat = {'supercategory': 'none', 'id': cid , 'name': cate} # no + 1json_dict['categories'].append(cat)bnd_id = START_BOUNDING_BOX_IDjsonnamelist = 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 + 236image_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}\n\n'target.write(info)continueimg = Image.open(os.path.join(imgPath, image_name))width, height = img.sizeimage = {'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+1category_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_xhg = right_bottom_y - left_top_yann = {'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 + 1print(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)?
總結
以上是生活随笔為你收集整理的可视化COCO分割标注文件,以及单个json合成coco格式标注文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用websockets,后台实时发数据
- 下一篇: 数据集增广 之 多个图片贴到一张图上,以