博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
目标检测-数据准备系列(三)--coco2csv
阅读量:2051 次
发布时间:2019-04-28

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

直接贴源码:

# @TIME  :2019/7/21 15:34# @File  :coco2csv.py"""从coco instance.json生成voc--xml文件""""""首先得下载编译cocoapipip install cythongit clone https://github.com/cocodataset/cocoapi.gitcd coco/PythonAPImake"""import osimport shutilfrom tqdm import tqdmimport matplotlib.pyplot as pltimport cv2from PIL import Image, ImageDrawimport sysbag_path = "../cocoapi-master/PythonAPI/"if not bag_path in sys.path:    sys.path.append(bag_path)from pycocotools.coco import COCO# the path you want to save your results for coco to vocsave_cvs_path = "./"#保存csv路径csv_name = "csv_labels.csv"#csv名称# datasets_list=['train2014', 'val2014']datasets_list = ['train2017']#coco数据集里面图片# Store annotations and train2014/val2014/... in this folderdataDir = '../../coco/coco2017/'#coco数据集整体文件,里面包含annotations和图片文件夹#path = os.path.abspath(dataDir)def id2name(coco):    classes = dict()    for cls in coco.dataset['categories']:        classes[cls['id']] = cls['name']    return classesdef showimg(coco, dataset, img, classes, cls_id, show=True):    global dataDir    I = Image.open('%s/%s/%s' % (dataDir, dataset, img['file_name']))    # 通过id,得到注释的信息    annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None)    # print(annIds)    anns = coco.loadAnns(annIds)    # print(anns)    # coco.showAnns(anns)    objs = []    for ann in anns:        class_name = classes[ann['category_id']]        if 'bbox' in ann:            bbox = ann['bbox']            xmin = int(bbox[0])            ymin = int(bbox[1])            xmax = int(bbox[2] + bbox[0])            ymax = int(bbox[3] + bbox[1])            obj = [class_name, xmin, ymin, xmax, ymax]            objs.append(obj)            draw = ImageDraw.Draw(I)            draw.rectangle([xmin, ymin, xmax, ymax])    if show:        plt.figure()        plt.axis('off')        plt.imshow(I)        plt.show()    return objscsv_labels = open(save_cvs_path +"/"+csv_name, "w")for dataset in datasets_list:    # ./COCO/annotations/instances_train2014.json    annFile = '{}/annotations/instances_{}.json'.format(dataDir, dataset)    #images = '{}/train{}'.format(dataDir, dataset)    images = dataDir+"train2017"#存放图片的文件夹路径,必须是纯图片    # COCO API for initializing annotated data    coco = COCO(annFile)    '''    COCO 对象创建完毕后会输出如下信息:    loading annotations into memory...    Done (t=0.81s)    creating index...    index created!    至此, json 脚本解析完毕, 并且将图片和对应的标注数据关联起来.    '''    # show all classes in coco    classes = id2name(coco)    classes_names = []    for key, value in classes.items():        classes_names.append(value)    classes_ids = coco.getCatIds(catNms=classes_names)    img_ids_totoal =[]    for cls in classes_names:        # Get ID number of this class        cls_id = coco.getCatIds(catNms=[cls])        img_ids = coco.getImgIds(catIds=cls_id)        for img_id in img_ids:            img_ids_totoal.append(img_id)    print(len(img_ids_totoal))    tem=set(img_ids_totoal)    temp = list(tem)    temp.sort()    print(len(tem))    print(len(temp))    for imgId in tqdm(temp):        img = coco.loadImgs(imgId)[0]        filename = img['file_name']        # print(filename)        abspath_img = os.path.abspath(images+"/"+filename)        objs = showimg(coco, dataset, img, classes, classes_ids, show=False)        #print(objs)        for ack in objs:            objectname = ack[0]            x1 = ack[1]            y1 = ack[2]            x2 = ack[3]            y2 = ack[4]            #print(x1,y1,x2,y2)            #print(objectname)            csv_labels.write(                abspath_img + "," + str(x1) + "," + str(y1) + "," + str(x2) + "," + str(y2) + "," + objectname + "\n")csv_labels.close()

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

你可能感兴趣的文章
剑指Offer 1.二维数组中的查找
查看>>
剑指offer 2.重建二叉树
查看>>
剑指offer 3.二叉树中和为某一值的路径
查看>>
剑指offer 4.替换空格
查看>>
剑指offer 5.从尾到头打印链表
查看>>
剑指offer 6.用两个栈实现队列
查看>>
剑指offer 7.旋转数组的最小数字
查看>>
剑指offer 8-11.斐波那契数列 跳台阶 变态跳台阶 矩形覆盖
查看>>
剑指offer 12.二进制中1的个数
查看>>
剑指offer 13.数值的整数次方
查看>>
剑指offer 14.调整数组顺序使奇数位于偶数前面
查看>>
剑指offer 15.链表中倒数第k个节点
查看>>
剑指offer 16.反转链表
查看>>
剑指offer 17.合并两个排好序的链表
查看>>
剑指offer 18.树的子结构
查看>>
剑指offer 19.二叉树的镜像
查看>>
剑指offer 20.顺时针打印矩阵
查看>>
剑指offer 21.包含min函数的栈
查看>>
剑指offer 23.从上往下打印二叉树
查看>>
剑指offer 25.二叉树中和为某一值的路径
查看>>