提取COCO 数据集的部分类

1.python提取COCO数据集中特定的类

安装pycocotools github地址:https://github.com/philferriere/cocoapi


pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI

若报错,pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI

换成

pip install git+git://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI

实在不行的话,手动下载

git clone https://github.com/pdollar/coco.git
cd coco/PythonAPI
python setup.py build_ext --inplace #安装到本地
python setup.py build_ext install # 安装到Python环境中

没有的库自己pip

注意skimage用pip install scikit-image -i https://pypi.tuna.tsinghua.edu.cn/simple

提取特定的类别如下:

# conding='utf-8'
from pycocotools.coco import COCO
import os
import shutil
from tqdm import tqdm
import skimage.io as io
import matplotlib.pyplot as plt
import cv2
from PIL import Image, ImageDraw#the path you want to save your results for coco to voc
savepath="/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/"  #save_path
img_dir=savepath+'images/'
anno_dir=savepath+'Annotations/'
# datasets_list=['train2014', 'val2014']
datasets_list=['train2017', 'val2017']classes_names = ['sheep']  #coco
#Store annotations and train2014/val2014/... in this folder
dataDir= '/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/coco/'  #origin cocoheadstr = """\
<annotation><folder>VOC</folder><filename>%s</filename><source><database>My Database</database><annotation>COCO</annotation><image>flickr</image><flickrid>NULL</flickrid></source><owner><flickrid>NULL</flickrid><name>company</name></owner><size><width>%d</width><height>%d</height><depth>%d</depth></size><segmented>0</segmented>
"""
objstr = """\<object><name>%s</name><pose>Unspecified</pose><truncated>0</truncated><difficult>0</difficult><bndbox><xmin>%d</xmin><ymin>%d</ymin><xmax>%d</xmax><ymax>%d</ymax></bndbox></object>
"""tailstr = '''\
</annotation>
'''#if the dir is not exists,make it,else delete it
def mkr(path):if os.path.exists(path):shutil.rmtree(path)os.mkdir(path)else:os.mkdir(path)
mkr(img_dir)
mkr(anno_dir)
def id2name(coco):classes=dict()for cls in coco.dataset['categories']:classes[cls['id']]=cls['name']return classesdef write_xml(anno_path,head, objs, tail):f = open(anno_path, "w")f.write(head)for obj in objs:f.write(objstr%(obj[0],obj[1],obj[2],obj[3],obj[4]))f.write(tail)def save_annotations_and_imgs(coco,dataset,filename,objs):#eg:COCO_train2014_000000196610.jpg-->COCO_train2014_000000196610.xmlanno_path=anno_dir+filename[:-3]+'xml'img_path=dataDir+dataset+'/'+filenameprint(img_path)dst_imgpath=img_dir+filenameimg=cv2.imread(img_path)#if (img.shape[2] == 1):#    print(filename + " not a RGB image")#   returnshutil.copy(img_path, dst_imgpath)head=headstr % (filename, img.shape[1], img.shape[0], img.shape[2])tail = tailstrwrite_xml(anno_path,head, objs, tail)def showimg(coco,dataset,img,classes,cls_id,show=True):global dataDirI=Image.open('%s/%s/%s'%(dataDir,dataset,img['file_name']))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 class_name in classes_names:print(class_name)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 objsfor dataset in datasets_list:#./COCO/annotations/instances_train2014.jsonannFile='{}/annotations/instances_{}.json'.format(dataDir,dataset)#COCO API for initializing annotated datacoco = COCO(annFile)#show all classes in cococlasses = id2name(coco)print(classes)#[1, 2, 3, 4, 6, 8]classes_ids = coco.getCatIds(catNms=classes_names)print(classes_ids)for cls in classes_names:#Get ID number of this classcls_id=coco.getCatIds(catNms=[cls])img_ids=coco.getImgIds(catIds=cls_id)print(cls,len(img_ids))# imgIds=img_ids[0:10]for imgId in tqdm(img_ids):img = coco.loadImgs(imgId)[0]filename = img['file_name']# print(filename)objs=showimg(coco, dataset, img, classes,classes_ids,show=False)print(objs)save_annotations_and_imgs(coco, dataset, filename, objs)

然后就可以了

2. 将上面获取的数据集划分为训练集和测试集
#conding='utf-8'
import os
import random
from shutil import copy2# origin
image_original_path = "/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/images"
label_original_path = "/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/Annotations"# parent_path = os.path.dirname(os.getcwd())
# parent_path = "D:\\AI_Find"
# train_image_path = os.path.join(parent_path, "image_data/seed/train/images/")
# train_label_path = os.path.join(parent_path, "image_data/seed/train/labels/")
train_image_path = os.path.join("/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/train2017")
train_label_path = os.path.join("/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/annotations/train2017")
test_image_path = os.path.join("/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/val2017")
test_label_path = os.path.join("/opt/10T/home/asc005/YangMingxiang/DenseCLIP_/data/COCO/annotations/val2017")# test_image_path = os.path.join(parent_path, 'image_data/seed/val/images/')
# test_label_path = os.path.join(parent_path, 'image_data/seed/val/labels/')def mkdir():if not os.path.exists(train_image_path):os.makedirs(train_image_path)if not os.path.exists(train_label_path):os.makedirs(train_label_path)if not os.path.exists(test_image_path):os.makedirs(test_image_path)if not os.path.exists(test_label_path):os.makedirs(test_label_path)def main():mkdir()all_image = os.listdir(image_original_path)for i in range(len(all_image)):num = random.randint(1,5)if num != 2:copy2(os.path.join(image_original_path, all_image[i]), train_image_path)train_index.append(i)else:copy2(os.path.join(image_original_path, all_image[i]), test_image_path)val_index.append(i)all_label = os.listdir(label_original_path)for i in train_index:copy2(os.path.join(label_original_path, all_label[i]), train_label_path)for i in val_index:copy2(os.path.join(label_original_path, all_label[i]), test_label_path)if __name__ == '__main__':train_index = []val_index = []main()
3.将上一步提取的COCO 某一类 xml转为COCO标准的json文件:
# -*- coding: utf-8 -*-
# @Time    : 2019/8/27 10:48
# @Author  :Rock
# @File    : voc2coco.py
# just for object detection
import xml.etree.ElementTree as ET
import os
import jsoncoco = dict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []category_set = dict()
image_set = set()category_item_id = 0
image_id = 0
annotation_id = 0def addCatItem(name):global category_item_idcategory_item = dict()category_item['supercategory'] = 'none'category_item_id += 1category_item['id'] = category_item_idcategory_item['name'] = namecoco['categories'].append(category_item)category_set[name] = category_item_idreturn category_item_iddef addImgItem(file_name, size):global image_idif file_name is None:raise Exception('Could not find filename tag in xml file.')if size['width'] is None:raise Exception('Could not find width tag in xml file.')if size['height'] is None:raise Exception('Could not find height tag in xml file.')img_id = "%04d" % image_idimage_id += 1image_item = dict()image_item['id'] = int(img_id)# image_item['id'] = image_idimage_item['file_name'] = file_nameimage_item['width'] = size['width']image_item['height'] = size['height']coco['images'].append(image_item)image_set.add(file_name)return image_iddef addAnnoItem(object_name, image_id, category_id, bbox):global annotation_idannotation_item = dict()annotation_item['segmentation'] = []seg = []# bbox[] is x,y,w,h# left_topseg.append(bbox[0])seg.append(bbox[1])# left_bottomseg.append(bbox[0])seg.append(bbox[1] + bbox[3])# right_bottomseg.append(bbox[0] + bbox[2])seg.append(bbox[1] + bbox[3])# right_topseg.append(bbox[0] + bbox[2])seg.append(bbox[1])annotation_item['segmentation'].append(seg)annotation_item['area'] = bbox[2] * bbox[3]annotation_item['iscrowd'] = 0annotation_item['ignore'] = 0annotation_item['image_id'] = image_idannotation_item['bbox'] = bboxannotation_item['category_id'] = category_idannotation_id += 1annotation_item['id'] = annotation_idcoco['annotations'].append(annotation_item)def parseXmlFiles(xml_path):for f in os.listdir(xml_path):if not f.endswith('.xml'):continuebndbox = dict()size = dict()current_image_id = Nonecurrent_category_id = Nonefile_name = Nonesize['width'] = Nonesize['height'] = Nonesize['depth'] = Nonexml_file = os.path.join(xml_path, f)# print(xml_file)tree = ET.parse(xml_file)root = tree.getroot()if root.tag != 'annotation':raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))# elem is <folder>, <filename>, <size>, <object>for elem in root:current_parent = elem.tagcurrent_sub = Noneobject_name = Noneif elem.tag == 'folder':continueif elem.tag == 'filename':file_name = elem.textif file_name in category_set:raise Exception('file_name duplicated')# add img item only after parse <size> tagelif current_image_id is None and file_name is not None and size['width'] is not None:if file_name not in image_set:current_image_id = addImgItem(file_name, size)# print('add image with {} and {}'.format(file_name, size))else:raise Exception('duplicated image: {}'.format(file_name))# subelem is <width>, <height>, <depth>, <name>, <bndbox>for subelem in elem:bndbox['xmin'] = Nonebndbox['xmax'] = Nonebndbox['ymin'] = Nonebndbox['ymax'] = Nonecurrent_sub = subelem.tagif current_parent == 'object' and subelem.tag == 'name':object_name = subelem.textif object_name not in category_set:current_category_id = addCatItem(object_name)else:current_category_id = category_set[object_name]elif current_parent == 'size':if size[subelem.tag] is not None:raise Exception('xml structure broken at size tag.')size[subelem.tag] = int(subelem.text)# option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>for option in subelem:if current_sub == 'bndbox':if bndbox[option.tag] is not None:raise Exception('xml structure corrupted at bndbox tag.')bndbox[option.tag] = int(option.text)# only after parse the <object> tagif bndbox['xmin'] is not None:if object_name is None:raise Exception('xml structure broken at bndbox tag')if current_image_id is None:raise Exception('xml structure broken at bndbox tag')if current_category_id is None:raise Exception('xml structure broken at bndbox tag')bbox = []# xbbox.append(bndbox['xmin'])# ybbox.append(bndbox['ymin'])# wbbox.append(bndbox['xmax'] - bndbox['xmin'])# hbbox.append(bndbox['ymax'] - bndbox['ymin'])# print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,#                                                bbox))addAnnoItem(object_name, current_image_id, current_category_id, bbox)if __name__ == '__main__':#修改这里的两个地址,一个是xml文件的父目录;一个是生成的json文件的绝对路径xml_path = r'G:\dataset\COCO\person\coco_val2014\annotations\\'json_file = r'G:\dataset\COCO\person\coco_val2014\instances_val2014.json'parseXmlFiles(xml_path)json.dump(coco, open(json_file, 'w'))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/840690.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【CTF Web】CTFShow web5 Writeup(SQL注入+PHP+位运算)

web5 1 阿呆被老板狂骂一通&#xff0c;决定改掉自己大意的毛病&#xff0c;痛下杀手&#xff0c;修补漏洞。 解法 注意到&#xff1a; <!-- flag in id 1000 -->拦截很多种字符&#xff0c;连 select 也不给用了。 if(preg_match("/\|\"|or|\||\-|\\\|\/|\…

24款奔驰S450升级原厂后排娱乐系统 主动氛围灯有哪些功能

24款奔驰S400豪华升级原厂主动氛围灯与后排娱乐系统&#xff1a;画蛇添足还是锦上添花&#xff1f; 在当今汽车市场竞争激烈的环境下&#xff0c;汽车制造商们为了满足消费者的多元化需求&#xff0c;不断推出各种升级配置和豪华版本。24款奔驰S400豪华版作为奔驰S级的一款重要…

听说部门来了个00后测试开发,一顿操作给我整麻了

公司新来了个同事&#xff0c;听说大学是学的广告专业&#xff0c;因为喜欢IT行业就找了个培训班&#xff0c;后来在一家小公司实习半年&#xff0c;现在跳槽来我们公司。来了之后把现有项目的性能优化了一遍&#xff0c;服务器缩减一半&#xff0c;性能反而提升4倍&#xff01…

uniapp开发vue3监听右滑返回操作,返回到指定页面

想要在uniapp框架中监听左滑或者右滑手势&#xff0c;需要使用touchstart和touchend两个api&#xff0c;因为没有原生的左右滑监听api&#xff0c;所以我们只能依靠这两个api来获取滑动开始时候的x坐标和滑动结束后的x坐标做比对&#xff0c;右滑的话&#xff0c;结束时候的x坐…

飞速提升中文打字,Master of Typing in Chinese for Mac助你一臂之力

Master of Typing in Chinese for Mac是一款专为Mac用户设计的中文打字练习软件。其主要功能包括帮助用户提高打字速度和准确性&#xff0c;培养盲打技巧&#xff0c;使键盘输入更加高效。 打字速度提升&#xff1a;软件提供多种练习模式&#xff0c;如字母、特殊字符、单词和…

FPGA状态机设计详解

一.什么是状态机&#xff1f; 想象一下你正在玩一个电子游戏&#xff0c;角色有多种状态&#xff0c;比如“行走”、“跳跃”、“攻击”等。每当你按下不同的按键或者满足某些条件时&#xff0c;角色的状态就会改变&#xff0c;并执行与该状态对应的动作。这就是状态机的一个简…

Java 类加载和实例化对象的过程

1. 类加载实例化过程 当我们编写完一个*.java类后。编译器&#xff08;如javac&#xff09;会将其转化为字节码。转化的字节码存储在.class后缀的文件中&#xff08;.class 二进制文件&#xff09;。接下来在类的加载过程中虚拟机JVM利用ClassLoader读取该.class文件将其中的字…

GAW-1000D 微机控制钢绞线拉力试验机

一、整机外观图与示意图 外观示意图 性能说明&#xff1a; GAW-1000D型微机控制电液伺服钢绞线拉力试验机主要用于对预应力钢绞线进行抗拉强度测试。由宽调速范围的电液比例伺服阀与计算机及测控单元所组成伺服控制系统&#xff0c;能精确的控制和测量试验全过程。整机由主机…

Unity3D雨雪粒子特效(Particle System)

系列文章目录 unity工具 文章目录 系列文章目录&#x1f449;前言&#x1f449;一、下雨的特效1-1.首先就是创建一个自带的粒子系统,整几张贴图,设置一下就能实现想要的效果了1-2 接着往下看视频效果 &#x1f449;二、下雪的特效&#x1f449;三、下雪有积雪的效果3-1 先把控…

docxtemplater避坑!!! 前端导出word怎么插入本地图片或base64 有完整示例

用docxtemplater库实现前端通过模板导出word&#xff0c;遇到需求&#xff0c;要插图片并转成word并导出&#xff0c;在图片转换这块遇到了问题&#xff0c;网上查示例大多都跑不通&#xff0c;自己琢磨半天&#xff0c;总算搞明白了。 附上清晰完整示例&#xff0c;供参考。 …

SpringCloudAlibaba:6.2RocketMQ的普通消息的使用

简介 普通消息也叫并发消息&#xff0c;是发送效率最高&#xff0c;使用最多的一种 依赖 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSch…

【强化学习的数学原理-赵世钰】课程笔记(三)贝尔曼最优公式

目录 学习引用内容梗概1. 第三章主要有两个内容2. 第二章大纲 二.激励性实例&#xff08;Motivating examples&#xff09;三.最优策略&#xff08;optimal policy&#xff09;的定义四.贝尔曼最优公式&#xff08;BOE&#xff09;&#xff1a;简介五.贝尔曼最优公式&#xff0…

专为汽车内容打造的智能剪辑解决方案

汽车内容创作已成为越来越多车主和汽车爱好者热衷的活动。然而&#xff0c;如何高效、便捷地将行车途中的精彩瞬间转化为高质量的视频作品&#xff0c;一直是困扰着广大用户的一大难题。美摄科技凭借其深厚的视频处理技术和智能分析能力&#xff0c;推出了专为汽车内容记录而生…

C语言数据结构栈的概念及结构、栈的实现、栈的初始化、销毁栈、入栈、出栈、检查是否为空、获取栈顶元素、获取有效元素个数等的介绍

文章目录 前言栈的概念及结构栈的实现一、 栈结构创建二、 初始化结构三、销毁栈四、入栈五、出栈六、检查是否为空七、获取栈顶元素八、获取有效元素的个数九、测试 1十、测试 2总结 前言 C语言数据结构栈的概念及结构、栈的实现、栈的初始化、销毁栈、入栈、出栈、检查是否为…

意外发现openGauss兼容Oracle的几个条件表达式

意外发现openGauss兼容Oracle的几个条件表达式 最近工作中发现openGauss在兼容oracle模式下&#xff0c;可以兼容常用的两个表达式&#xff0c;因此就随手测试了一下。 查看数据库版本 [ommopenGauss ~]$ gsql -r gsql ((openGauss 6.0.0-RC1 build ed7f8e37) compiled at 2…

数据结构----堆的实现(附代码)

当大家看了鄙人的上一篇博客栈后&#xff0c;稍微猜一下应该知道鄙人下一篇想写的博客就是堆了吧。毕竟堆栈在C语言中常常是一起出现的。那么堆是什么&#xff0c;是如何实现的嘞。接下来我就带大家去尝试实现一下堆。 堆的含义 首先我们要写出一个堆&#xff0c;那么我们就需…

kubernetes之prometheus kube-controller-manager。 scheduler报错问题

项目场景&#xff1a; prometheus scheduler及kube-controller-manager监控报错 问题描述 kubeadm搭建完kube-prometheus 会有这个报错 原因分析&#xff1a; rootmaster2:~# kubectl describe servicemonitor -n kube-system kube-controller-manager通过以上图片我们发现 k…

php TP8 阿里云短信服务SDKV 2.0

安装&#xff1a;composer require alibabacloud/dysmsapi-20170525 2.0.24 官方文档&#xff1a;短信服务_SDK中心-阿里云OpenAPI开发者门户 (aliyun.com) 特别注意&#xff1a;传入参数获得值形式 正确&#xff1a; $PhoneNumbers $postData[PhoneNumbers];$signName $po…

单片机设计注意事项

1.电源线可以30mil走线&#xff0c;信号线可以6mil走线 2.LDO推荐 SGM2019-3.3,RT9013,RT9193,1117-3.3V。 3.单片机VCC要充分滤波后再供电&#xff0c;可以接0.1uf的电容 4.晶振附件不要走其他元件&#xff0c;且放置完单片机后就放置晶振&#xff0c;晶振靠近X1,X2。

【全网最全】2024电工杯数学建模A题前三题完整解答matlab+21页初步参考论文+py代码等(后续会更新成品论文)

您的点赞收藏是我继续更新的最大动力&#xff01; 一定要点击如下的卡片链接&#xff0c;那是获取资料的入口&#xff01; 【全网最全】2024电工杯数学建模A题前三题完整解答matlab21页初步参考论文py代码等&#xff08;后续会更新成品论文&#xff09;「首先来看看目前已有的…