本文整理汇总了Python中pycocotools.coco方法的典型用法代码示例。如果您正苦于以下问题:Python pycocotools.coco方法的具体用法?Python pycocotools.coco怎么用?Python pycocotools.coco使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools
的用法示例。
在下文中一共展示了pycocotools.coco方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _dump_json
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def _dump_json(self):
"""Write coco json file"""
if not self._current_id == len(self._img_ids):
warnings.warn(
'Recorded {} out of {} validation images, incomplete results'.format(
self._current_id, len(self._img_ids)))
import json
try:
if self._use_ext:
with open(self._bbox_filename, 'w') as f:
json.dump(self._bbox_result, f)
with open(self._segm_filename, 'w') as f:
json.dump(self._segm_result, f)
else:
with open(self._filename, 'w') as f:
json.dump(self._results, f)
except IOError as e:
raise RuntimeError("Unable to dump json file, ignored. What(): {}".format(str(e)))
示例2: get_example
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def get_example(self, i):
img_id = self.img_ids[i]
ann_ids = self.coco.getAnnIds(imgIds=img_id)
anns = self.coco.loadAnns(ann_ids)
img_fname = self.img_fname.format(img_id)
img = skimage.io.imread(img_fname)
if img.ndim == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
example = self._annotations_to_example(
anns, img.shape[0], img.shape[1])
# img, bboxes, labels, masks
# or img, bboxes, labels, masks, crowds
# or img, bboxes, labels, masks, areas
# or img, bboxes, labels, masks, crowds, areas
return tuple([img] + example)
示例3: __init__
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def __init__(self, dataset, save_prefix, use_time=True, cleanup=False,
use_ext=False, starting_id=0, score_thresh=1e-3):
self._starting_id = starting_id
self._use_ext = use_ext
super(COCOInstanceMetric, self).__init__('COCOInstance')
self.dataset = dataset
self._dump_to_file = not cleanup
if use_time:
import datetime
t = datetime.datetime.now().strftime('_%Y_%m_%d_%H_%M_%S')
else:
t = ''
self._img_ids = sorted(dataset.coco.getImgIds())
self._current_id = starting_id
self._results = []
self._score_thresh = score_thresh
from ...data.mscoco.utils import try_import_pycocotools
try_import_pycocotools()
import pycocotools.mask as cocomask
self._cocomask = cocomask
self._filename = osp.abspath(osp.expanduser(save_prefix) + t + '.json')
if use_ext:
from pycocotools import coco
if not hasattr(coco, 'ext'):
raise AttributeError('external module is not support by the COCO API installed. '
'Consider install NVIDIA MSCOCO API here '
'https://github.com/NVIDIA/cocoapi.git')
self.dataset.coco.createIndex(use_ext=use_ext)
self._bbox_result = []
self._segm_result = []
self._bbox_filename = osp.abspath(osp.expanduser(save_prefix) + t + '_bbox.json')
self._segm_filename = osp.abspath(osp.expanduser(save_prefix) + t + '_segm.json')
if not self._dump_to_file:
warnings.warn('When using external module, eval json is always dumped.')
示例4: _update
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def _update(self, annType='bbox'):
"""Use coco to get real scores. """
if self._use_ext:
self.dataset.coco.createIndex(use_ext=True)
if annType == 'bbox':
pred = self.dataset.coco.loadRes(self._bbox_filename, use_ext=True)
else:
pred = self.dataset.coco.loadRes(self._segm_filename, use_ext=True)
else:
if self._results is not None and not self._dump_to_file:
pred = self.dataset.coco.loadRes(self._results)
else:
pred = self.dataset.coco.loadRes(self._filename)
gt = self.dataset.coco
# lazy import pycocotools
from ...data.mscoco.utils import try_import_pycocotools
try_import_pycocotools()
from pycocotools.cocoeval import COCOeval
# only NVIDIA MSCOCO API support use_ext
coco_eval = COCOeval(gt, pred, annType, use_ext=self._use_ext) \
if self._use_ext else COCOeval(gt, pred, annType)
coco_eval.evaluate()
coco_eval.accumulate()
names, values = [], []
names.append('~~~~ Summary {} metrics ~~~~\n'.format(annType))
# catch coco print string, don't want directly print here
_stdout = sys.stdout
sys.stdout = io.StringIO()
coco_eval.summarize()
coco_summary = sys.stdout.getvalue()
sys.stdout = _stdout
values.append(str(coco_summary).strip())
names.append('~~~~ Mean AP for {} ~~~~\n'.format(annType))
values.append('{:.1f}'.format(100 * self._get_ap(coco_eval)))
return names, values
示例5: _encode_mask
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def _encode_mask(self, mask):
"""Convert mask to coco rle"""
rle = self._cocomask.encode(np.array(mask[:, :, np.newaxis], order='F'))[0]
rle['counts'] = rle['counts'].decode('ascii')
return rle
# pylint: disable=arguments-differ, unused-argument
示例6: __init__
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def __init__(self, images_dir, annotation_file, image_shape, keep_aspect_ratio=False):
self.images_dir = images_dir
self.annotation_file = annotation_file
self.image_shape = tuple(image_shape)
self.keep_aspect_ratio = keep_aspect_ratio
self.cocoGt = pycocotools.coco.COCO('annotations/person_keypoints_val2017.json')
self.catIds = self.cocoGt.getCatIds('person')
self.imgIds = self.cocoGt.getImgIds(catIds=self.catIds)
self.transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
示例7: from_coco
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def from_coco(DetectionMetrics, true_coco, pred_coco):
"""
Create detection metrics from two coco files representing the truth and
predictions.
Args:
true_coco (ndsampler.CocoDataset):
pred_coco (ndsampler.CocoDataset):
Example:
>>> # xdoctest: +REQUIRES(module:ndsampler)
>>> import ndsampler
>>> true_coco = ndsampler.CocoDataset.demo('shapes')
>>> pred_coco = true_coco
>>> self = DetectionMetrics.from_coco(true_coco, pred_coco)
>>> self.score_voc()
"""
import kwimage
classes = true_coco.object_categories()
self = DetectionMetrics(classes)
def _coco_to_dets(coco_dset):
for img in coco_dset.imgs.values():
gid = img['id']
imgname = img['file_name']
aids = coco_dset.gid_to_aids[gid]
annots = [coco_dset.anns[aid] for aid in aids]
dets = kwimage.Detections.from_coco_annots(annots, dset=coco_dset)
yield dets, imgname, gid
for dets, imgname, gid in _coco_to_dets(true_coco):
self.add_truth(dets, imgname, gid=gid)
for dets, imgname, gid in _coco_to_dets(pred_coco):
self.add_predictions(dets, imgname, gid=gid)
return self
示例8: __init__
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def __init__(self, split,
use_crowd=False, return_crowd=False, return_area=False):
if split == 'train':
split = split + '2014'
data_type = 'train2014'
elif split in ['val', 'minival', 'valminusminival']:
split = split + '2014'
data_type = 'val2014'
else:
raise ValueError
ann_file = osp.join(
self.root_dir, 'annotations/instances_%s.json' % split)
if not osp.exists(ann_file):
self.download()
self._use_crowd = use_crowd
self._return_crowd = return_crowd
self._return_area = return_area
# suppress loading message of annotations
with open(os.devnull, 'w') as f:
sys.stdout = f
self.coco = COCO(ann_file)
sys.stdout = sys.__stdout__
self.img_fname = osp.join(
self.root_dir, data_type, 'COCO_%s_{:012}.jpg' % data_type)
# set class_names
cats = self.coco.loadCats(self.coco.getCatIds())
cat_id_to_class_id = {}
class_names = []
for cat in sorted(cats, key=lambda x: x['id']):
class_id = len(class_names)
cat_id_to_class_id[cat['id']] = class_id
class_names.append(cat['name'])
class_names = np.asarray(class_names)
class_names.setflags(write=0)
self.cat_id_to_class_id = cat_id_to_class_id
self.class_names = class_names
# filter images without any annotations
img_ids = []
for img_id in self.coco.getImgIds():
ann_ids = self.coco.getAnnIds(img_id)
if len(ann_ids) >= 1:
img_ids.append(img_id)
self.img_ids = img_ids
示例9: _to_coco
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def _to_coco(dmet):
"""
Convert to a coco representation of truth and predictions
"""
import ndsampler
true = ndsampler.CocoDataset()
pred = ndsampler.CocoDataset()
for node in dmet.classes:
# cid = dmet.classes.graph.node[node]['id']
cid = dmet.classes.index(node)
supercategory = list(dmet.classes.graph.pred[node])
if len(supercategory) == 0:
supercategory = None
else:
assert len(supercategory) == 1
supercategory = supercategory[0]
true.add_category(node, id=cid, supercategory=supercategory)
pred.add_category(node, id=cid, supercategory=supercategory)
for imgname, gid in dmet._imgname_to_gid.items():
true.add_image(imgname, id=gid)
pred.add_image(imgname, id=gid)
idx_to_id = {
idx: dmet.classes.index(node)
for idx, node in enumerate(dmet.classes.idx_to_node)
}
for gid, pred_dets in dmet.gid_to_pred_dets.items():
pred_boxes = pred_dets.boxes
if 'scores' in pred_dets.data:
pred_scores = pred_dets.scores
else:
pred_scores = np.ones(len(pred_dets))
pred_cids = list(ub.take(idx_to_id, pred_dets.class_idxs))
pred_xywh = pred_boxes.to_xywh().data.tolist()
for bbox, cid, score in zip(pred_xywh, pred_cids, pred_scores):
pred.add_annotation(gid, cid, bbox=bbox, score=score)
for gid, true_dets in dmet.gid_to_true_dets.items():
true_boxes = true_dets.boxes
if 'weights' in true_dets.data:
true_weights = true_dets.weights
else:
true_weights = np.ones(len(true_boxes))
true_cids = list(ub.take(idx_to_id, true_dets.class_idxs))
true_xywh = true_boxes.to_xywh().data.tolist()
for bbox, cid, weight in zip(true_xywh, true_cids, true_weights):
true.add_annotation(gid, cid, bbox=bbox, weight=weight)
return pred, true
示例10: score_coco
# 需要导入模块: import pycocotools [as 别名]
# 或者: from pycocotools import coco [as 别名]
def score_coco(dmet, verbose=0):
"""
score using ms-coco method
Example:
>>> # xdoctest: +REQUIRES(--pycocotools)
>>> dmet = DetectionMetrics.demo(
>>> nimgs=100, nboxes=(0, 3), n_fp=(0, 1), nclasses=8)
>>> print(dmet.score_coco()['mAP'])
0.711016...
"""
from pycocotools import coco
from pycocotools import cocoeval
# The original pycoco-api prints to much, supress it
import netharn as nh
pred, true = dmet._to_coco()
quiet = verbose == 0
with nh.util.SupressPrint(coco, cocoeval, enabled=quiet):
cocoGt = true._aspycoco()
cocoDt = pred._aspycoco()
for ann in cocoGt.dataset['annotations']:
w, h = ann['bbox'][-2:]
ann['ignore'] = ann['weight'] < .5
ann['area'] = w * h
ann['iscrowd'] = False
for ann in cocoDt.dataset['annotations']:
w, h = ann['bbox'][-2:]
ann['area'] = w * h
evaler = cocoeval.COCOeval(cocoGt, cocoDt, iouType='bbox')
evaler.evaluate()
evaler.accumulate()
evaler.summarize()
coco_ap = evaler.stats[1]
coco_scores = {
'mAP': coco_ap,
'evalar_stats': evaler.stats
}
return coco_scores