本文整理汇总了Python中pycocotools.coco.COCO.getCatIds方法的典型用法代码示例。如果您正苦于以下问题:Python COCO.getCatIds方法的具体用法?Python COCO.getCatIds怎么用?Python COCO.getCatIds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.coco.COCO
的用法示例。
在下文中一共展示了COCO.getCatIds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_coco
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def load_coco(self, dataset_dir, subset, class_ids=None,
class_map=None, return_coco=False):
"""Load a subset of the COCO dataset.
dataset_dir: The root directory of the COCO dataset.
subset: What to load (train, val, minival, val35k)
class_ids: If provided, only loads images that have the given classes.
class_map: TODO: Not implemented yet. Supports maping classes from
different datasets to the same class ID.
return_coco: If True, returns the COCO object.
"""
# Path
image_dir = os.path.join(dataset_dir, "train2014" if subset == "train"
else "val2014")
# Create COCO object
json_path_dict = {
"train": "annotations/instances_train2014.json",
"val": "annotations/instances_val2014.json",
"minival": "annotations/instances_minival2014.json",
"val35k": "annotations/instances_valminusminival2014.json",
}
coco = COCO(os.path.join(dataset_dir, json_path_dict[subset]))
# Load all classes or a subset?
if not class_ids:
# All classes
class_ids = sorted(coco.getCatIds())
# All images or a subset?
if class_ids:
image_ids = []
for id in class_ids:
image_ids.extend(list(coco.getImgIds(catIds=[id])))
# Remove duplicates
image_ids = list(set(image_ids))
else:
# All images
image_ids = list(coco.imgs.keys())
# Add classes
for i in class_ids:
self.add_class("coco", i, coco.loadCats(i)[0]["name"])
# Add images
for i in image_ids:
self.add_image(
"coco", image_id=i,
path=os.path.join(image_dir, coco.imgs[i]['file_name']),
width=coco.imgs[i]["width"],
height=coco.imgs[i]["height"],
annotations=coco.loadAnns(coco.getAnnIds(
imgIds=[i], catIds=class_ids, iscrowd=None)))
if return_coco:
return coco
示例2: _load_gt_roidb
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def _load_gt_roidb(self):
_coco = COCO(self._anno_file)
# deal with class names
cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())]
class_to_coco_ind = dict(zip(cats, _coco.getCatIds()))
class_to_ind = dict(zip(self.classes, range(self.num_classes)))
coco_ind_to_class_ind = dict([(class_to_coco_ind[cls], class_to_ind[cls])
for cls in self.classes[1:]])
image_ids = _coco.getImgIds()
gt_roidb = [self._load_annotation(_coco, coco_ind_to_class_ind, index) for index in image_ids]
return gt_roidb
示例3: Resize_Image
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
class Resize_Image():
def __init__(self, imgeDir, resizeImageDir):
self.ImageDir = imgeDir
self.ResizeImageDir = resizeImageDir
self.dataDir = APP_ROOT + "/Data/"
self.dataType = 'val2014'
self.annFile = '%s/annotations/instances_%s.json'\
% (self.dataDir, self.dataType)
# initialize COCO api for instance annotations
self.coco = COCO(self.annFile)
# display COCO categories and supercategories
self.cats = self.coco.loadCats(self.coco.getCatIds())
self.names = [cat['name'] for cat in self.cats]
self.ids = [cat['id'] for cat in self.cats]
self.name_ids = {}
# get all images containing given categories, select one at random
self.img_dict = {}
def resize_image(self):
for i in range(len(self.names)):
if self.ids[i] not in self.name_ids:
self.name_ids.update({self.names[i]: self.ids[i]})
self.__image_dict_update()
def __image_dict_update(self):
for name in self.names:
catIds = self.coco.getCatIds(catNms=[name])
imgIds = self.coco.getImgIds(catIds=catIds)
for i in range(len(imgIds)):
img = self.coco.loadImgs(imgIds[i])[0]
if img["file_name"] not in self.img_dict:
self.img_dict.update({img["file_name"]: name})
self.__output_resize_images()
def __output_resize_images(self):
for k, v in sorted(self.img_dict.items(), key=lambda x: x[0]):
ImageFile = '%s/%s' % (self.ImageDir, k)
pil_im = Image.open(ImageFile)
out = pil_im.resize((255, 255))
save_image = '%s/%s' % (self.ResizeImageDir, k)
out.save(save_image)
print(save_image + " " + str(self.name_ids[v]))
示例4: main
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def main(argv):
## Parsing the command
in_path = ''
out_path = ''
ann_path = ''
try:
opts, args = getopt.getopt(argv,"hi:o:a:",["in=","out=","annotation="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile> -a <annotationfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile> -a <annotationfile>'
sys.exit()
elif opt in ("-i", "--in"):
in_path = arg
elif opt in ("-o", "--out"):
out_path = arg
elif opt in ("-a", "--annotation"):
ann_path = arg
print('Performing evaluation using Coco Python API...')
_COCO = COCO(ann_path)
_cats = _COCO.loadCats(_COCO.getCatIds())
_classes = tuple(['__background__'] + [c['name'] for c in _cats])
_do_eval(in_path,out_path, _COCO, _classes)
示例5: _load_jsons
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def _load_jsons(self):
"""Load all image paths and labels from JSON annotation files into buffer."""
items = []
labels = []
segms = []
# lazy import pycocotools
try_import_pycocotools()
from pycocotools.coco import COCO
for split in self._splits:
anno = os.path.join(self._root, 'annotations', split) + '.json'
_coco = COCO(anno)
self._coco.append(_coco)
classes = [c['name'] for c in _coco.loadCats(_coco.getCatIds())]
if not classes == self.classes:
raise ValueError("Incompatible category names with COCO: ")
assert classes == self.classes
json_id_to_contiguous = {
v: k for k, v in enumerate(_coco.getCatIds())}
if self.json_id_to_contiguous is None:
self.json_id_to_contiguous = json_id_to_contiguous
self.contiguous_id_to_json = {
v: k for k, v in self.json_id_to_contiguous.items()}
else:
assert self.json_id_to_contiguous == json_id_to_contiguous
# iterate through the annotations
image_ids = sorted(_coco.getImgIds())
for entry in _coco.loadImgs(image_ids):
dirname, filename = entry['coco_url'].split('/')[-2:]
abs_path = os.path.join(self._root, dirname, filename)
if not os.path.exists(abs_path):
raise IOError('Image: {} not exists.'.format(abs_path))
label, segm = self._check_load_bbox(_coco, entry)
# skip images without objects
if self._skip_empty and label is None:
continue
items.append(abs_path)
labels.append(label)
segms.append(segm)
return items, labels, segms
示例6: load_coco
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def load_coco(self, dataset_dir, subset, year=DEFAULT_DATASET_YEAR, class_ids=None,
class_map=None, return_coco=False, auto_download=False):
"""Load a subset of the COCO dataset.
dataset_dir: The root directory of the COCO dataset.
subset: What to load (train, val, minival, valminusminival)
year: What dataset year to load (2014, 2017) as a string, not an integer
class_ids: If provided, only loads images that have the given classes.
class_map: TODO: Not implemented yet. Supports maping classes from
different datasets to the same class ID.
return_coco: If True, returns the COCO object.
auto_download: Automatically download and unzip MS-COCO images and annotations
"""
if auto_download is True:
self.auto_download(dataset_dir, subset, year)
coco = COCO("{}/annotations/instances_{}{}.json".format(dataset_dir, subset, year))
if subset == "minival" or subset == "valminusminival":
subset = "val"
image_dir = "{}/{}{}".format(dataset_dir, subset, year)
# Load all classes or a subset?
if not class_ids:
# All classes
class_ids = sorted(coco.getCatIds())
# All images or a subset?
if class_ids:
image_ids = []
for id in class_ids:
image_ids.extend(list(coco.getImgIds(catIds=[id])))
# Remove duplicates
image_ids = list(set(image_ids))
else:
# All images
image_ids = list(coco.imgs.keys())
# Add classes
for i in class_ids:
self.add_class("coco", i, coco.loadCats(i)[0]["name"])
# Add images
for i in image_ids:
self.add_image(
"coco", image_id=i,
path=os.path.join(image_dir, coco.imgs[i]['file_name']),
width=coco.imgs[i]["width"],
height=coco.imgs[i]["height"],
annotations=coco.loadAnns(coco.getAnnIds(
imgIds=[i], catIds=class_ids, iscrowd=None)))
if return_coco:
return coco
示例7: coco2kitti
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def coco2kitti(catNms, annFile):
# initialize COCO api for instance annotations
coco = COCO(annFile)
# Create an index for the category names
cats = coco.loadCats(coco.getCatIds())
cat_idx = {}
for c in cats:
cat_idx[c['id']] = c['name']
for img in coco.imgs:
# Get all annotation IDs for the image
catIds = coco.getCatIds(catNms=catNms)
annIds = coco.getAnnIds(imgIds=[img], catIds=catIds)
# If there are annotations, create a label file
if len(annIds) > 0:
# Get image filename
img_fname = coco.imgs[img]['file_name']
# open text file
with open('./labels/' + img_fname.split('.')[0] + '.txt','w') as label_file:
anns = coco.loadAnns(annIds)
for a in anns:
bbox = a['bbox']
# Convert COCO bbox coords to Kitti ones
bbox = [bbox[0], bbox[1], bbox[2] + bbox[0], bbox[3] + bbox[1]]
bbox = [str(b) for b in bbox]
catname = cat_idx[a['category_id']]
# Format line in label file
# Note: all whitespace will be removed from class names
out_str = [catname.replace(" ","")
+ ' ' + ' '.join(['0']*3)
+ ' ' + ' '.join([b for b in bbox])
+ ' ' + ' '.join(['0']*8)
+'\n']
label_file.write(out_str[0])
示例8: main
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def main():
if len(sys.argv) != 3:
print 'usage: python convert_to_pascalformat.py coco_dataDir coco_dataType'
print 'for example: python convert_to_pascalformat.py \'./\' \'val2014\''
sys.exit(1)
dataDir = sys.argv[1]
dataType = sys.argv[2]
from pycocotools.coco import COCO
import os
annFile='%s/annotations/instances_%s.json'%(dataDir,dataType)
coco=COCO(annFile)
cats = coco.loadCats(coco.getCatIds())
nms=[cat['name'] for cat in cats]
imgIds = coco.getImgIds()
directory = './annotations_pascalformat/'
if not os.path.exists(directory):
os.makedirs(directory)
for n in xrange(len(imgIds)):
img = coco.loadImgs(imgIds[n])[0]
annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None)
anns = coco.loadAnns(annIds)
xml = '<annotation>\n<folder>\nCOCO2014pascalformat\n</folder>\n<filename>\n'
xml += img['file_name'] + '\n</filename>\n<source>\n<database>\nCOCO2014pascalformat\n</database>\n</source>\n<size>\n'
xml += '<width>\n' + str(img['width']) + '\n</width>\n' + '<height>\n' + str(img['height']) + '\n</height>\n'
xml += '<depth>\n3\n</depth>\n</size>\n<segmented>\n0\n</segmented>\n'
for i in xrange(len(anns)):
bbox = anns[i]['bbox']
xml += '<object>\n<name>\n' + str(anns[i]['category_id']) + '\n</name>\n'
xml += '<bndbox>\n<xmin>\n' + str(int(round(bbox[0]))) + '\n</xmin>\n'
xml += '<ymin>\n' + str(int(round(bbox[1]))) + '\n</ymin>\n'
xml += '<xmax>\n' + str(int(round(bbox[0] + bbox[2]))) + '\n</xmax>\n'
xml += '<ymax>\n' + str(int(round(bbox[1] + bbox[3]))) + '\n</ymax>\n</bndbox>\n'
xml += '<truncated>\n0\n</truncated>\n<difficult>\n0\n</difficult>\n</object>\n'
xml += '</annotation>'
f_xml = open(directory + img['file_name'].split('.jpg')[0] + '.xml', 'w')
f_xml.write(xml)
f_xml.close()
print str(n) + ' out of ' + str(len(imgIds))
示例9: process_coco
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def process_coco(data_dir, out_dir, num_shards, is_train=True):
if is_train:
data_type = 'train2014'
out_path = join(out_dir, 'train_%04d_wmeta.tfrecord')
else:
data_type = 'val2014'
out_path = join(out_dir, 'val_%04d_wmeta.tfrecord')
anno_file = join(data_dir,
'annotations/person_keypoints_%s.json' % data_type)
img_dir = join(data_dir, 'images', data_type)
# initialize COCO api for person keypoints annotations
coco = COCO(anno_file)
catIds = coco.getCatIds(catNms=['person'])
img_inds = coco.getImgIds(catIds=catIds)
# Only run on 'single person's
coder = ImageCoder()
i = 0
# Count on shards
fidx = 0
num_ppl = 0
total_num_ppl = 0
while i < len(img_inds):
tf_filename = out_path % fidx
print('Starting tfrecord file %s' % tf_filename)
with tf.python_io.TFRecordWriter(tf_filename) as writer:
# Count on total ppl in each shard
num_ppl = 0
while i < len(img_inds) and num_ppl < num_shards:
if i % 100 == 0:
print('Reading img %d/%d' % (i, len(img_inds)))
num_ppl += add_to_tfrecord(coco, img_inds[i], img_dir, coder,
writer, is_train)
i += 1
total_num_ppl += num_ppl
fidx += 1
print('Made %d shards, with total # of people: %d' %
(fidx - 1, total_num_ppl))
示例10: LoadImageList
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def LoadImageList(dataDir, dataType):
# dataDir = '/home/gnoses/DB/MS COCO'
# dataType = 'train2014'
annFile = '%s/annotations/instances_%s.json' % (dataDir, dataType)
# initialize COCO api for instance annotations
coco = COCO(annFile)
# display COCO categories and supercategories
cats = coco.loadCats(coco.getCatIds())
# nms = [cat['name'] for cat in cats]
# print 'COCO categories: \n\n', ' '.join(nms)
categoryNames = {}
for cat in cats:
categoryNames[cat['id']] = cat['name']
# nms = set([cat['supercategory'] for cat in cats])
# print 'COCO supercategories: \n', ' '.join(nms)
imgIds = coco.getImgIds()
imgs = coco.loadImgs(imgIds)
return coco, imgs
示例11: load_coco
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
def load_coco(self, dataset_dir, subset, year=DEFAULT_DATASET_YEAR, class_ids=None,
class_map=None, return_coco=False, auto_download=False):
"""Load a subset of the COCO dataset.
dataset_dir: The root directory of the COCO dataset.
subset: What to load (train, val, minival, valminusminival)
year: What dataset year to load (2014, 2017) as a string, not an integer
class_ids: If provided, only loads images that have the given classes.
class_map: TODO: Not implemented yet. Supports maping classes from
different datasets to the same class ID.
return_coco: If True, returns the COCO object.
auto_download: Automatically download and unzip MS-COCO images and annotations
"""
if auto_download is True:
self.auto_download(dataset_dir, subset, year)
coco = COCO("{}/annotations/{}_{}{}.json".format(dataset_dir, self.task_type, subset, year))
if subset == "minival" or subset == "valminusminival":
subset = "val"
image_dir = "{}/{}{}".format(dataset_dir, subset, year)
# Load all classes or a subset?
if not class_ids:
# All classes
class_ids = sorted(coco.getCatIds())
# print(class_ids)
# All images or a subset?
if class_ids:
image_ids = []
for id in class_ids:
image_ids.extend(list(coco.getImgIds(catIds=[id])))
# Remove duplicates
image_ids = list(set(image_ids))
else:
# All images
image_ids = list(coco.imgs.keys())
# Add classes
for i in class_ids:
self.add_class("coco", i, coco.loadCats(i)[0]["name"])
# Add images
for i in image_ids:
self.add_image(
"coco", image_id=i,
path=os.path.join(image_dir, coco.imgs[i]['file_name']),
width=coco.imgs[i]["width"],
height=coco.imgs[i]["height"],
annotations=coco.loadAnns(coco.getAnnIds(
imgIds=[i], catIds=class_ids, iscrowd=None)))
if(self.task_type == "person_keypoints"):
#the connection between 2 close keypoints
self._skeleton = coco.loadCats(Person_ID)[0]["skeleton"]
#keypoint names
# ["nose","left_eye","right_eye","left_ear","right_ear","left_shoulder",
# "right_shoulder","left_elbow","right_elbow","left_wrist","right_wrist",
# "left_hip","right_hip","left_knee","right_knee","left_ankle","right_ankle"]
self._keypoint_names = coco.loadCats(Person_ID)[0]["keypoints"]
self._skeleton = np.array(self._skeleton,dtype=np.int32)
print("Skeleton:",np.shape(self._skeleton))
print("Keypoint names:",np.shape(self._keypoint_names))
if return_coco:
return coco
示例12: coco
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
class coco(imdb):
def __init__(self, image_set, year):
imdb.__init__(self, 'coco_' + year + '_' + image_set)
# COCO specific config options
self.config = {'use_salt': True,
'cleanup': True}
# name, paths
self._year = year
self._image_set = image_set
self._data_path = osp.join(cfg.DATA_DIR, 'coco')
# load COCO API, classes, class <-> id mappings
self._COCO = COCO(self._get_ann_file())
cats = self._COCO.loadCats(self._COCO.getCatIds())
self._classes = tuple(['__background__'] + [c['name'] for c in cats])
self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes)))))
self._class_to_coco_cat_id = dict(list(zip([c['name'] for c in cats],
self._COCO.getCatIds())))
self._image_index = self._load_image_set_index()
# Default to roidb handler
self.set_proposal_method('gt')
self.competition_mode(False)
# Some image sets are "views" (i.e. subsets) into others.
# For example, minival2014 is a random 5000 image subset of val2014.
# This mapping tells us where the view's images and proposals come from.
self._view_map = {
'minival2014': 'val2014', # 5k val2014 subset
'valminusminival2014': 'val2014', # val2014 \setminus minival2014
'test-dev2015': 'test2015',
}
coco_name = image_set + year # e.g., "val2014"
self._data_name = (self._view_map[coco_name]
if coco_name in self._view_map
else coco_name)
# Dataset splits that have ground-truth annotations (test splits
# do not have gt annotations)
self._gt_splits = ('train', 'val', 'minival')
def _get_ann_file(self):
prefix = 'instances' if self._image_set.find('test') == -1 \
else 'image_info'
return osp.join(self._data_path, 'annotations',
prefix + '_' + self._image_set + self._year + '.json')
def _load_image_set_index(self):
"""
Load image ids.
"""
image_ids = self._COCO.getImgIds()
return image_ids
def _get_widths(self):
anns = self._COCO.loadImgs(self._image_index)
widths = [ann['width'] for ann in anns]
return widths
def image_path_at(self, i):
"""
Return the absolute path to image i in the image sequence.
"""
return self.image_path_from_index(self._image_index[i])
def image_path_from_index(self, index):
"""
Construct an image path from the image's "index" identifier.
"""
# Example image path for index=119993:
# images/train2014/COCO_train2014_000000119993.jpg
file_name = ('COCO_' + self._data_name + '_' +
str(index).zfill(12) + '.jpg')
image_path = osp.join(self._data_path, 'images',
self._data_name, file_name)
assert osp.exists(image_path), \
'Path does not exist: {}'.format(image_path)
return image_path
def gt_roidb(self):
"""
Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.
"""
cache_file = osp.join(self.cache_path, self.name + '_gt_roidb.pkl')
if osp.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = pickle.load(fid)
print('{} gt roidb loaded from {}'.format(self.name, cache_file))
return roidb
gt_roidb = [self._load_coco_annotation(index)
for index in self._image_index]
with open(cache_file, 'wb') as fid:
pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL)
print('wrote gt roidb to {}'.format(cache_file))
return gt_roidb
def _load_coco_annotation(self, index):
"""
Loads COCO bounding-box instance annotations. Crowd instances are
handled by marking their overlaps (with all categories) to -1. This
#.........这里部分代码省略.........
示例13: print
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
imgDir = '/data/dota/dota_clip_coco/val/'
annFile='/data/dota/dota_clip_coco/annotations/dota_rbbox_val.json'
# imgDir = '/home/jwwangchn/data/VOCdevkit/UAV-Bottle/UAV-Bottle-V2.0.0/JPEGImages/'
# annFile='/home/jwwangchn/data/VOCdevkit/UAV-Bottle/UAV-Bottle-V2.0.0/uav_bd_train_rbbox.json'
imgDir = '/home/jwwangchn/data/dota/dota_clip_coco/train/'
annFile='/home/jwwangchn/data/dota/dota_clip_coco/annotations/dota_rbbox_train.json'
# initialize COCO api for instance annotations
coco=COCO(annFile)
# display COCO categories and supercategories
cats = coco.loadCats(coco.getCatIds())
nms=[cat['name'] for cat in cats]
print('COCO categories: \n{}\n'.format(' '.join(nms)))
nms = set([cat['supercategory'] for cat in cats])
print('COCO supercategories: \n{}'.format(' '.join(nms)))
# get all images containing given categories, select one at random
catIds = coco.getCatIds(catNms=['vehicle']);
imgIds = coco.getImgIds(catIds=catIds);
for imgId in imgIds:
imgIds = coco.getImgIds(imgIds = [2018019951]) # 555705, cat
img = coco.loadImgs(imgIds[np.random.randint(0,len(imgIds))])[0]
示例14: __init__
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
#.........这里部分代码省略.........
def _filterCatIds(self, catIds):
"""
Sets a list of categories ids to the intersection of itself with the list of GoogleRefexp category ids.
Raises warning if the category id list contains ids outside GoogleRefexp dataset.
"""
catIds = catIds if isinstance(catIds, list) else [catIds]
if len(catIds) == 0:
return self.catIds
catIdsSet = set(catIds)
refexpCatsSet = set(self.catIds)
notRefexpCats = catIdsSet - refexpCatsSet
if len(notRefexpCats) > 0:
warnings.warn('Category ids ' + str(notRefexpCats) + ' are not part of the GoogleRefexp dataset and will be ignored from the answer.', RuntimeWarning)
catIds = catIdsSet.intersection(refexpCatsSet)
return list(catIds)
# Below wrappers of the COCO toolkit methods, adding referring expression ids as additional filter.
# Filters default to the set of GoogleRefexp images, annotations and categories(subset of COCO).
def getAnnIds(self, imgIds=[], catIds=[], refexpIds=[], areaRng=[], iscrowd=None):
"""
Same as COCO.getAnnIds(). Gets only annotations that appear in GoogleRefexp.
Adds filtering by referring expression ids.
"""
refexpIds = refexpIds if isinstance(refexpIds, list) else [refexpIds]
imgIds = self._filterImgIds(imgIds)
if len(refexpIds) == 0:
return self._filterAnnIds(self.coco.getAnnIds(imgIds, catIds, areaRng, iscrowd), warn=False)
annsForRefexps = set([])
for refexp_id in refexpIds:
annsForRefexps.add(self.refexpToAnnId[refexp_id])
return list(annsForRefexps.intersection(set(self.coco.getAnnIds(imgIds, catIds, areaRng, iscrowd))))
def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""
Same as COCO.getAnnIds(). Gets only categories that appear in GoogleRefexp.
"""
catIds = self._filterCatIds(catIds)
return self.coco.getCatIds(catNms, supNms, catIds)
def getImgIds(self, imgIds=[], catIds=[], refexpIds=[]):
"""
Same as COCO.getImgIds(). Gets only images that appear in GoogleRefexp.
Adds filtering by referring expression ids.
"""
refexpIds = refexpIds if isinstance(refexpIds, list) else [refexpIds]
imgIds = self._filterImgIds(imgIds)
if len(refexpIds) == 0:
return self.coco.getImgIds(imgIds, catIds)
imgsForRefexps = set([])
for refexp_id in refexpIds:
annForRefexp = self.refexpToAnnId[refexp_id]
imgsForRefexps.add(self.annToImgId[annForRefexp])
cocoImgs = set(self.coco.getImgIds(imgIds, catIds))
return list(cocoImgs.intersection(imgsForRefexps))
def loadAnns(self, ids=[]):
"""
Load annotations with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
"""
ids = self._filterAnnIds(ids)
annotations = self.dataset['annotations']
if type(ids) == list:
return [annotations[id] for id in ids]
示例15: open
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import getCatIds [as 别名]
import pdb
pylab.rcParams['figure.figsize'] = (10.0,8.0)
dataDir='..'
dataType='val2014'
#dataType='train2014'
saveImgPath = '%s/JPEGImages/' %(dataDir)
saveAnnoPath = '%s/Annotations/'%(dataDir)
annFile='%s/annotations/instances_%s.json'%(dataDir,dataType)
coco=COCO(annFile)
listOut = open('%s/ImageSets/Main/%sIndoor.txt'%(dataDir, dataType), 'w')
indoorCatIds = [62, 63, 67, 72, 78, 82]
# display category information
cats = coco.loadCats(coco.getCatIds())
nms=[cat['name'] for cat in cats]
print 'COCO categories: \n\n', ' '.join(nms)
nms = set([cat['supercategory'] for cat in cats])
print 'COCO supercategories: \n', ' '.join(nms)
indoorCats = coco.loadCats(indoorCatIds)
nms = [cat['name'] for cat in indoorCats]
print 'COCO selected indoor categories: \n', ' '.join(nms)
outdoorSupCat = ['outdoor', 'sports', 'vehicle'] #[0, 4, 7]
outdoorAnimalCat = [16, 19, 20, 21, 22, 23, 24, 25]
outdoorCatIds = coco.getCatIds(supNms = outdoorSupCat)
outdoorCatIds += outdoorAnimalCat
## for debug ###
imgIds = coco.getImgIds()
img = coco.loadImgs(imgIds[0])[0]