本文整理汇总了Python中pycocotools.coco.COCO.loadImgs方法的典型用法代码示例。如果您正苦于以下问题:Python COCO.loadImgs方法的具体用法?Python COCO.loadImgs怎么用?Python COCO.loadImgs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.coco.COCO
的用法示例。
在下文中一共展示了COCO.loadImgs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
def main():
random.seed(123)
dataDir='/home/gchrupala/repos/coco'
dataType='val2014'
cap = COCO('%s/annotations/captions_%s.json'%(dataDir,dataType))
coco = COCO('%s/annotations/instances_%s.json'%(dataDir,dataType))
imgCat = {}
for cat,imgs in coco.catToImgs.items():
for img in imgs:
if img in imgCat:
imgCat[img].add(cat)
else:
imgCat[img]=set([cat])
with open('hard2.csv','w') as file:
writer = csv.writer(file)
writer.writerow(["desc", "url_1", "url_2", "url_3", "url_4" ])
imgIds = random.sample(coco.getImgIds(), 1000)
for img in coco.loadImgs(imgIds):
if img['id'] not in imgCat:
continue
cats = imgCat[img['id']]
desc = random.sample(cap.imgToAnns[img['id']],1)[0]
imgs = coco.loadImgs(random.sample(sum([ coco.getImgIds(catIds=[cat])
for cat in cats ],[]),3))
urls = [ img['coco_url'] ] + [ img['coco_url'] for img in imgs ]
random.shuffle(urls)
writer.writerow([desc['caption']] + urls )
示例2: ablate
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
def ablate(imgIds = [], mode ='destroy', out_path="tmp", coco = coco, ct = None, **args):
"""[ablation entry point 2.0]
Created to accomodate background-destroying ablation. Will dispatch all
old ablations (gaussian, blackout, & median) to gen_ablation."""
if ct is None:
ct = coco_text.COCO_Text(os.path.join(CD, 'COCO_Text.json'))
if imgIds == []:
imgIds = ct.getImgIds(imgIds=ct.train, catIds=[('legibility','legible')])
imgIds = [imgIds[np.random.randint(0,len(imgIds))]]
#dispatch to old ablation entry point
if mode in ['gaussian', 'blackout', 'median']:
return gen_ablation(imgIds, mode, ct, out_path=out_path, **args)
#else do destroy_bg
if coco is None:
coco = COCO('%s/annotations/instances_%s.json'%(DATA_PATH,DATA_TYPE))
imgs = coco.loadImgs(imgIds)
results = []
for idx, img in enumerate(imgs):
print("Ablating image {}/{} with id {} ".format(idx+1, len(imgIds), img['id']))
ori_file_name = os.path.join(CD, DATA_PATH, DATA_TYPE, img['file_name'])
orig = io.imread(ori_file_name)
if mode == 'destroy':
ablt = destroy_bg(orig, img['id'], coco, **args)
elif mode == 'median_bg':
ablt = median_bg(orig, img['id'], coco, **args)
out_file_name = os.path.join(CD, "..", out_path, "%s_%s"%(mode, img['file_name']))
io.imsave(out_file_name, ablt)
results.append((img['id'], ori_file_name, out_file_name))
return results
示例3: Resize_Image
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [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: _load_all
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
def _load_all(self, anno_file, shuffle):
"""
initialize all entries given annotation json file
Parameters:
----------
anno_file: str
annotation json file
shuffle: bool
whether to shuffle image list
"""
image_set_index = []
labels = []
coco = COCO(anno_file)
img_ids = coco.getImgIds()
for img_id in img_ids:
# filename
image_info = coco.loadImgs(img_id)[0]
filename = image_info["file_name"]
subdir = filename.split('_')[1]
height = image_info["height"]
width = image_info["width"]
# label
anno_ids = coco.getAnnIds(imgIds=img_id)
annos = coco.loadAnns(anno_ids)
label = []
for anno in annos:
cat_id = int(anno["category_id"])
bbox = anno["bbox"]
assert len(bbox) == 4
xmin = float(bbox[0]) / width
ymin = float(bbox[1]) / height
xmax = xmin + float(bbox[2]) / width
ymax = ymin + float(bbox[3]) / height
label.append([cat_id, xmin, ymin, xmax, ymax, 0])
if label:
labels.append(np.array(label))
image_set_index.append(os.path.join(subdir, filename))
if shuffle:
import random
indices = range(len(image_set_index))
random.shuffle(indices)
image_set_index = [image_set_index[i] for i in indices]
labels = [labels[i] for i in indices]
# store the results
self.image_set_index = image_set_index
self.labels = labels
示例5: main
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [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))
示例6: __init__
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
def __init__(self, train, **kwargs):
super().__init__()
self.image_size = kwargs.get("image_size", None)
self.data_root = kwargs.get("data_root", "./data")
self.max_vocab = kwargs.get("max_vocab", "10000")
if self.max_vocab == -1:
self.max_vocab = None
self.phase = "train" if train else "val"
json_path = "{}/annotations/captions_{}2014.json".format(self.data_root, self.phase)
# load data with COCO API
print("[!] Prepare COCO {} dataset".format(self.phase))
coco = COCO(json_path)
self.path, self.text = list(), list()
for key, value in coco.anns.items():
image_idx = value["image_id"]
path = coco.loadImgs(image_idx)[0]["file_name"]
self.text.append(value["caption"])
self.path.append(path)
# preprocess (tokenize) text
for i, t in enumerate(self.text):
self.text[i] = CaptionDataset.TEXT.preprocess(t)
# build vocab with GLOVE
# NOTE: only performed in training phase
if self.phase == "train":
CaptionDataset.TEXT.build_vocab(
self.text,
vectors="glove.6B.300d",
max_size=self.max_vocab)
print("[!] Dataset preparation done!")
print("\t# of data: {}".format(len(self.text)))
print("\tVocab size: {}\n".format(len(CaptionDataset.TEXT.vocab)))
# image transform function
self.transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406),
(0.229, 0.224, 0.225))])
示例7: LoadImageList
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [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
示例8: _load_jsons
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [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
示例9: set
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
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]
I = io.imread('%s/images/%s/%s'%(dataDir,dataType,img['file_name']))
plt.figure(); plt.imshow(I); plt.imsave('a.png', I)
annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None)
anns = coco.loadAnns(annIds)
coco.showAnns(anns)
plt.savefig('b.png')
## ###
indoorImgIds = set()
for catId in indoorCatIds:
indoorImgIds |= set(coco.getImgIds(catIds=catId))
print 'cat id: %d, image number: %d\n' % (catId, len(indoorImgIds))
for catId in outdoorCatIds:
outdoorIds = coco.getImgIds(imgIds=list(imgIds), catIds=catId)
indoorAndOutdoor = indoorImgIds & set(outdoorIds)
示例10: CoCoDataset
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
class CoCoDataset(data.Dataset):
_TRAIN_MODES = ['train', 'train_small']
def __init__(self, transform, mode, batch_size, vocab_threshold, vocab_file, start_word,
end_word, unk_word, annotations_file, vocab_from_file, img_folder):
self.transform = transform
self.mode = mode
self.batch_size = batch_size
self.vocab = Vocabulary(vocab_threshold, vocab_file, start_word,
end_word, unk_word, annotations_file, vocab_from_file)
self.img_folder = img_folder
if self.mode in self._TRAIN_MODES:
self.coco = COCO(annotations_file)
self.ids = list(self.coco.anns.keys())
print('Obtaining caption lengths...')
all_tokens = [nltk.tokenize.word_tokenize(str(self.coco.anns[self.ids[index]]['caption']).lower()) for index in tqdm(np.arange(len(self.ids)))]
self.caption_lengths = [len(token) for token in all_tokens]
else:
test_info = json.loads(open(annotations_file).read())
self.paths = [item['file_name'] for item in test_info['images']]
def __getitem__(self, index):
# obtain image and caption if in training mode
if self.mode in self._TRAIN_MODES:
ann_id = self.ids[index]
caption = self.coco.anns[ann_id]['caption']
img_id = self.coco.anns[ann_id]['image_id']
path = self.coco.loadImgs(img_id)[0]['file_name']
# Convert image to tensor and pre-process using transform
image = Image.open(os.path.join(self.img_folder, path)).convert('RGB')
image = self.transform(image)
# Convert caption to tensor of word ids.
tokens = nltk.tokenize.word_tokenize(str(caption).lower())
caption = []
caption.append(self.vocab(self.vocab.start_word))
caption.extend([self.vocab(token) for token in tokens])
caption.append(self.vocab(self.vocab.end_word))
caption = torch.Tensor(caption).long()
# return pre-processed image and caption tensors
return image, caption
# obtain image if in test mode
else:
path = self.paths[index]
# Convert image to tensor and pre-process using transform
PIL_image = Image.open(os.path.join(self.img_folder, path)).convert('RGB')
orig_image = np.array(PIL_image)
image = self.transform(PIL_image)
# return original image and pre-processed image tensor
return orig_image, image
def get_train_indices(self):
sel_length = np.random.choice(self.caption_lengths)
all_indices = np.where([self.caption_lengths[i] == sel_length for i in np.arange(len(self.caption_lengths))])[0]
indices = list(np.random.choice(all_indices, size=self.batch_size))
return indices
def __len__(self):
if self.mode == 'train':
return len(self.ids)
else:
return len(self.paths)
示例11: range
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
annFile='%s/annotations/instances_%s.json'%(dataDir,dataType)
# In[3]:
# initialize COCO api for instance annotations
coco=COCO(annFile)
# get all images containing given categories, select one at random
catIds = coco.getCatIds(catNms=['person'])
imgIds = coco.getImgIds(catIds=catIds)
data=[]
for i in range(1,len(imgIds)):
print "Processing image ",i,"/",len(imgIds)
id_image=imgIds[i]
img = coco.loadImgs(id_image)[0]
print img['file_name']
shutil.copy('%s/images/%s/%s'%(dataDir,dataType,img['file_name']),'../person_image')
annIds = coco.getAnnIds(imgIds=id_image, catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
bbox_list=[]
for j in range(0,len(anns)):
bbox_list.append(anns[j]['bbox'])
data.append({'file_name':img['file_name'],'image_id':id_image,'bbox':bbox_list})
import io, json
with io.open('bboxes.json', 'w', encoding='utf-8') as f:
f.write(unicode(json.dumps(data, ensure_ascii=False)))
示例12: print
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
subject_id = interaction["subject_id"]
subject_anns = coco.loadAnns(subject_id)[0]
object_id = interaction["object_id"]
object_anns = coco.loadAnns(object_id)[0]
object_cat = coco.cats[object_anns["category_id"]]["name"]
v_actions = interaction["visual_actions"]
v_adverbs = interaction["visual_adverbs"]
print("Image ID: [{0}]".format(image_id))
print("Subject ID:[{0}]".format(subject_id))
print("Object ID: [{0}], Category: [{1}]".format(object_id, object_cat))
print("\nVisual Actions:")
for va_id in v_actions:
va = [x for x in visual_actions if x["id"] == va_id][0]
print(" - id:[{0}], name:[{1}]".format(va["id"], va["name"]))
print("\nVisual Adverbs:")
for va_id in v_adverbs:
va = [x for x in visual_adverbs if x["id"] == va_id][0]
print(" - id:[{0}], name:[{1}]".format(va["id"], va["name"]))
img = coco.loadImgs(image_id)[0]
I = io.imread("{0}/{1}/{2}".format(COCO_IMG_DIR, "train2014", img["file_name"]))
plt.figure(figsize=(12, 8))
plt.imshow(I)
coco.showAnns([subject_anns, object_anns])
plt.show()
示例13: JsonDataset
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
class JsonDataset(object):
"""A class representing a COCO json dataset."""
def __init__(self, name):
assert name in DATASETS.keys(), \
'Unknown dataset name: {}'.format(name)
assert os.path.exists(DATASETS[name][IM_DIR]), \
'Image directory \'{}\' not found'.format(DATASETS[name][IM_DIR])
assert os.path.exists(DATASETS[name][ANN_FN]), \
'Annotation file \'{}\' not found'.format(DATASETS[name][ANN_FN])
logger.debug('Creating: {}'.format(name))
self.name = name
self.image_directory = DATASETS[name][IM_DIR]
self.image_prefix = (
'' if IM_PREFIX not in DATASETS[name] else DATASETS[name][IM_PREFIX]
)
self.COCO = COCO(DATASETS[name][ANN_FN])
self.debug_timer = Timer()
# Set up dataset classes
category_ids = self.COCO.getCatIds()
categories = [c['name'] for c in self.COCO.loadCats(category_ids)]
self.category_to_id_map = dict(zip(categories, category_ids))
self.classes = ['__background__'] + categories
self.num_classes = len(self.classes)
self.json_category_id_to_contiguous_id = {
v: i + 1
for i, v in enumerate(self.COCO.getCatIds())
}
self.contiguous_category_id_to_json_id = {
v: k
for k, v in self.json_category_id_to_contiguous_id.items()
}
self._init_keypoints()
def get_roidb(
self,
gt=False,
proposal_file=None,
min_proposal_size=2,
proposal_limit=-1,
crowd_filter_thresh=0
):
"""Return an roidb corresponding to the json dataset. Optionally:
- include ground truth boxes in the roidb
- add proposals specified in a proposals file
- filter proposals based on a minimum side length
- filter proposals that intersect with crowd regions
"""
assert gt is True or crowd_filter_thresh == 0, \
'Crowd filter threshold must be 0 if ground-truth annotations ' \
'are not included.'
image_ids = self.COCO.getImgIds()
image_ids.sort()
roidb = copy.deepcopy(self.COCO.loadImgs(image_ids))
for entry in roidb:
self._prep_roidb_entry(entry)
if gt:
# Include ground-truth object annotations
self.debug_timer.tic()
for entry in roidb:
self._add_gt_annotations(entry)
logger.debug(
'_add_gt_annotations took {:.3f}s'.
format(self.debug_timer.toc(average=False))
)
if proposal_file is not None:
# Include proposals from a file
self.debug_timer.tic()
self._add_proposals_from_file(
roidb, proposal_file, min_proposal_size, proposal_limit,
crowd_filter_thresh
)
logger.debug(
'_add_proposals_from_file took {:.3f}s'.
format(self.debug_timer.toc(average=False))
)
_add_class_assignments(roidb)
return roidb
def _prep_roidb_entry(self, entry):
"""Adds empty metadata fields to an roidb entry."""
# Reference back to the parent dataset
entry['dataset'] = self
# Make file_name an abs path
entry['image'] = os.path.join(
self.image_directory, self.image_prefix + entry['file_name']
)
entry['flipped'] = False
entry['has_visible_keypoints'] = False
# Empty placeholders
entry['boxes'] = np.empty((0, 4), dtype=np.float32)
entry['segms'] = []
entry['gt_classes'] = np.empty((0), dtype=np.int32)
entry['seg_areas'] = np.empty((0), dtype=np.float32)
entry['gt_overlaps'] = scipy.sparse.csr_matrix(
np.empty((0, self.num_classes), dtype=np.float32)
)
entry['is_crowd'] = np.empty((0), dtype=np.bool)
# 'box_to_gt_ind_map': Shape is (#rois). Maps from each roi to the index
# in the list of rois that satisfy np.where(entry['gt_classes'] > 0)
#.........这里部分代码省略.........
示例14: loadImgs
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
def loadImgs(self, ids=[]):
"""
Didn't change the original function, just call super
"""
return COCO.loadImgs(self,ids)
示例15: CocoGenerator
# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadImgs [as 别名]
class CocoGenerator(Generator):
""" Generate data from the COCO dataset.
See https://github.com/cocodataset/cocoapi/tree/master/PythonAPI for more information.
"""
def __init__(self, data_dir, set_name, **kwargs):
""" Initialize a COCO data generator.
Args
data_dir: Path to where the COCO dataset is stored.
set_name: Name of the set to parse.
"""
self.data_dir = data_dir
self.set_name = set_name
self.coco = COCO(os.path.join(data_dir, 'annotations', 'instances_' + set_name + '.json'))
self.image_ids = self.coco.getImgIds()
self.load_classes()
super(CocoGenerator, self).__init__(**kwargs)
def load_classes(self):
""" Loads the class to label mapping (and inverse) for COCO.
"""
# load class names (name -> label)
categories = self.coco.loadCats(self.coco.getCatIds())
categories.sort(key=lambda x: x['id'])
self.classes = {}
self.coco_labels = {}
self.coco_labels_inverse = {}
for c in categories:
self.coco_labels[len(self.classes)] = c['id']
self.coco_labels_inverse[c['id']] = len(self.classes)
self.classes[c['name']] = len(self.classes)
# also load the reverse (label -> name)
self.labels = {}
for key, value in self.classes.items():
self.labels[value] = key
def size(self):
""" Size of the COCO dataset.
"""
return len(self.image_ids)
def num_classes(self):
""" Number of classes in the dataset. For COCO this is 80.
"""
return len(self.classes)
def name_to_label(self, name):
""" Map name to label.
"""
return self.classes[name]
def label_to_name(self, label):
""" Map label to name.
"""
return self.labels[label]
def coco_label_to_label(self, coco_label):
""" Map COCO label to the label as used in the network.
COCO has some gaps in the order of labels. The highest label is 90, but there are 80 classes.
"""
return self.coco_labels_inverse[coco_label]
def coco_label_to_name(self, coco_label):
""" Map COCO label to name.
"""
return self.label_to_name(self.coco_label_to_label(coco_label))
def label_to_coco_label(self, label):
""" Map label as used by the network to labels as used by COCO.
"""
return self.coco_labels[label]
def image_aspect_ratio(self, image_index):
""" Compute the aspect ratio for an image with image_index.
"""
image = self.coco.loadImgs(self.image_ids[image_index])[0]
return float(image['width']) / float(image['height'])
def load_image(self, image_index):
""" Load an image at the image_index.
"""
image_info = self.coco.loadImgs(self.image_ids[image_index])[0]
path = os.path.join(self.data_dir, 'images', self.set_name, image_info['file_name'])
return read_image_bgr(path)
def load_annotations(self, image_index):
""" Load annotations for an image_index.
"""
# get ground truth annotations
annotations_ids = self.coco.getAnnIds(imgIds=self.image_ids[image_index], iscrowd=False)
annotations = np.zeros((0, 5))
# some images appear to miss annotations (like image with id 257034)
if len(annotations_ids) == 0:
#.........这里部分代码省略.........