博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
coco数据集生成-原本有mask标注的单类多bbox--转换为每一个bbox扩边两倍为单独一个图生成新的coco形式json文件
阅读量:2050 次
发布时间:2019-04-28

本文共 4074 字,大约阅读时间需要 13 分钟。

# -*- coding: utf-8 -*-import sys, getoptimport osimport jsonimport cv2import randomimport numpy as npnp.random.seed(41)import globimport shutilimport os# -*- coding: utf-8 -*-import osimport sys, getoptfrom pycocotools.coco import COCO, maskUtilsimport cv2import numpy as npdef mkdir_os(path):    if not os.path.exists(path):        os.makedirs(path)def groberect(points, ww, hh):    x1 = points[0]    y1 = points[1]    w = points[2]    h = points[3]    x2 = x1 + w - 1    y2 = y1 + h - 1    px = float(x1 + x2) / 2    py = float(y1 + y2) / 2    w = w * 2    h = h * 2    l = max(0, px - w / 2)    r = min(ww - 1, px + w / 2) #x2    t = max(0, py - h / 2)    b = min(hh - 1, py + h / 2) #y2    w = r - l + 1    h = b - t + 1    # x1y1 x2y2    return [int(l), int(t), int(w), int(h)]def main(argv):    # json_file = './data/coco/annotations/instances_val2017.json'    # dataset_dir = './data/coco/val2017/'    # save_dir = './data/coco/vis/'    inputfile = ''    jsonfile = ''    outputfile = ''    try:        opts, args = getopt.getopt(argv, "hi:j:o:", ["ifile=", "jfile=", "ofile="])    except getopt.GetoptError:        print('test.py -i 
-j
-o
') sys.exit(2) for opt, arg in opts: if opt == '-h': print('test.py -i
-j
-o
') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-j", "--jfile"): jsonfile = arg elif opt in ("-o", "--ofile"): outputfile = arg print('\n输入的文件为:', inputfile) print('\n输入的json为:', jsonfile) print('\n输出的文件为:', outputfile) images = [] annotations = [] mkdir_os(outputfile) coco = COCO(jsonfile) catIds = coco.getCatIds(catNms=['wires']) # catIds=1 表示人这一类 imgIds = coco.getImgIds(catIds=catIds) # 图片id,许多值 image_id = 0 annotations_id = 0 for i in range(len(imgIds)): if i % 100 == 0: print(i, "/", len(imgIds)) img_info = coco.loadImgs(imgIds[i])[0] cvImage = cv2.imread(os.path.join(inputfile, img_info['file_name']), -1) cvImage = cv2.cvtColor(cvImage, cv2.COLOR_BGR2GRAY) cvImage = cv2.cvtColor(cvImage, cv2.COLOR_GRAY2BGR) ori_H, ori_W = cvImage.shape[:2] annIds = coco.getAnnIds(imgIds=img_info['id'], catIds=catIds, iscrowd=None) anns = coco.loadAnns(annIds) #原来一幅图可能拆成多个,需要保存多个图像,生成多个image信息,多个annotation信息 img_info_append = [] for index in range(len(anns)): ann = anns[index] img_temp = img_info.copy() if 'segmentation' in ann: #只处理存在annotation的情况 if type(ann['segmentation']) == list: #只处理points这种形式的mask标注的情况 bbox = ann['bbox'] new_bbox = groberect(bbox, ori_W, ori_H) img_temp['width'] = new_bbox[2] img_temp['height'] = new_bbox[3] img_temp['file_name'] = img_temp['file_name'].split('.')[0] + "_" + str(index) + ".jpg" img_temp['id'] = image_id #cropImg = img[(y):(y + hh), (x):(x + ww)] save_cvImage = cvImage[new_bbox[1]:(new_bbox[1] + new_bbox[3]), new_bbox[0]:(new_bbox[0] + new_bbox[2])] cv2.imwrite(os.path.join(outputfile, img_temp['file_name']), save_cvImage) img_info_append.append(img_temp) ann['bbox'] = [bbox[0]-new_bbox[0], bbox[1]-new_bbox[1], bbox[2], bbox[3]] for seg in range(len(ann['segmentation'])): ori_seg = ann['segmentation'][seg] for k in range(len(ori_seg)//2): ori_seg[2 * k] = ori_seg[2 * k] - new_bbox[0] ori_seg[2 * k + 1] = ori_seg[2 * k + 1] - new_bbox[1] ann['segmentation'][seg] = ori_seg ann['image_id'] = int(image_id) #anns[index] = ann else: exit() else: exit() image_id += 1 #annotations_id += 1 annotations.extend(anns) images.extend(img_info_append) instance = {} instance['info'] = 'spytensor created' instance['license'] = ['license'] instance['images'] = images instance['annotations'] = annotations instance['categories'] = coco.dataset['categories'] import io #json.dump(instance, io.open("./result.json", 'w', encoding='utf-8'), ensure_ascii=False, indent=1) # indent=2 更加美观显示 with io.open("./new_json.json", 'w', encoding="utf-8") as outfile: my_json_str = json.dumps(instance, ensure_ascii=False, indent=1) #python3 无 # if isinstance(my_json_str, str): # my_json_str = my_json_str.decode("utf-8") outfile.write(my_json_str)if __name__ == "__main__": main(sys.argv[1:])

 

转载地址:http://gwwlf.baihongyu.com/

你可能感兴趣的文章
[Kick Start 2020] Round A 2.Plates
查看>>
Leetcode C++ 《第181场周赛-1》 5364. 按既定顺序创建目标数组
查看>>
Leetcode C++ 《第181场周赛-2》 1390. 四因数
查看>>
阿里云《云原生》公开课笔记 第一章 云原生启蒙
查看>>
阿里云《云原生》公开课笔记 第二章 容器基本概念
查看>>
阿里云《云原生》公开课笔记 第三章 kubernetes核心概念
查看>>
阿里云《云原生》公开课笔记 第四章 理解Pod和容器设计模式
查看>>
阿里云《云原生》公开课笔记 第五章 应用编排与管理
查看>>
阿里云《云原生》公开课笔记 第六章 应用编排与管理:Deployment
查看>>
阿里云《云原生》公开课笔记 第七章 应用编排与管理:Job和DaemonSet
查看>>
阿里云《云原生》公开课笔记 第八章 应用配置管理
查看>>
阿里云《云原生》公开课笔记 第九章 应用存储和持久化数据卷:核心知识
查看>>
linux系统 阿里云源
查看>>
国内外helm源记录
查看>>
牛客网题目1:最大数
查看>>
散落人间知识点记录one
查看>>
Leetcode C++ 随手刷 547.朋友圈
查看>>
手抄笔记:深入理解linux内核-1
查看>>
内存堆与栈
查看>>
Leetcode C++《每日一题》20200621 124.二叉树的最大路径和
查看>>