本文整理汇总了Python中pycocotools.coco.loadAnns方法的典型用法代码示例。如果您正苦于以下问题:Python coco.loadAnns方法的具体用法?Python coco.loadAnns怎么用?Python coco.loadAnns使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.coco
的用法示例。
在下文中一共展示了coco.loadAnns方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visualize
# 需要导入模块: from pycocotools import coco [as 别名]
# 或者: from pycocotools.coco import loadAnns [as 别名]
def visualize(img_id):
img_descriptor = coco.loadImgs(img_id)
file_name = coco_data_folder + "val/" + img_descriptor[0]['file_name']
fig, ax = plt.subplots(1)
img = mpimg.imread(file_name)
ax.imshow(img)
gt_ann_ids = coco.getAnnIds(imgIds=[img_id])
gt_anns = coco.loadAnns(gt_ann_ids)
dets = detections_by_imgid[img_id]
print("Image", img_id, "Dets", len(dets), "GT", len(gt_anns))
for gt in gt_anns:
draw_box(ax, gt['bbox'], 'r', gt['category_id'], 1.0)
for det in dets:
draw_box(ax, det['bbox'], 'b', det['category_id'], det['score'])
plt.show()
示例2: cache
# 需要导入模块: from pycocotools import coco [as 别名]
# 或者: from pycocotools.coco import loadAnns [as 别名]
def cache(config, path, category_index):
phase = os.path.splitext(os.path.basename(path))[0]
data = []
for i, row in pd.read_csv(os.path.splitext(__file__)[0] + '.tsv', sep='\t').iterrows():
logging.info('loading data %d (%s)' % (i, ', '.join([k + '=' + str(v) for k, v in row.items()])))
root = os.path.expanduser(os.path.expandvars(row['root']))
year = str(row['year'])
suffix = phase + year
path = os.path.join(root, 'annotations', 'instances_%s.json' % suffix)
if not os.path.exists(path):
logging.warning(path + ' not exists')
continue
coco = pycocotools.coco.COCO(path)
catIds = coco.getCatIds(catNms=list(category_index.keys()))
cats = coco.loadCats(catIds)
id_index = dict((cat['id'], category_index[cat['name']]) for cat in cats)
imgIds = coco.getImgIds()
path = os.path.join(root, suffix)
imgs = coco.loadImgs(imgIds)
_imgs = list(filter(lambda img: os.path.exists(os.path.join(path, img['file_name'])), imgs))
if len(imgs) > len(_imgs):
logging.warning('%d of %d images not exists' % (len(imgs) - len(_imgs), len(imgs)))
for img in tqdm.tqdm(_imgs):
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
if len(anns) <= 0:
continue
path = os.path.join(path, img['file_name'])
width, height = img['width'], img['height']
bbox = np.array([ann['bbox'] for ann in anns], dtype=np.float32)
yx_min = bbox[:, 1::-1]
hw = bbox[:, -1:1:-1]
yx_max = yx_min + hw
cls = np.array([id_index[ann['category_id']] for ann in anns], dtype=np.int)
difficult = np.zeros(cls.shape, dtype=np.uint8)
try:
if config.getboolean('cache', 'verify'):
size = (height, width)
image = cv2.imread(path)
assert image is not None
assert image.shape[:2] == size[:2]
utils.cache.verify_coords(yx_min, yx_max, size[:2])
except configparser.NoOptionError:
pass
assert len(yx_min) == len(cls)
assert yx_min.shape == yx_max.shape
assert len(yx_min.shape) == 2 and yx_min.shape[-1] == 2
data.append(dict(path=path, yx_min=yx_min, yx_max=yx_max, cls=cls, difficult=difficult))
logging.warning('%d of %d images are saved' % (len(data), len(_imgs)))
return data
示例3: coco
# 需要导入模块: from pycocotools import coco [as 别名]
# 或者: from pycocotools.coco import loadAnns [as 别名]
def coco(writer, name_index, profile, row, verify=False):
root = os.path.expanduser(os.path.expandvars(row['root']))
year = str(row['year'])
name = profile + year
path = os.path.join(root, 'annotations', 'instances_%s.json' % name)
if not os.path.exists(path):
tf.logging.warn(path + ' not exists')
return False
import pycocotools.coco
coco = pycocotools.coco.COCO(path)
catIds = coco.getCatIds(catNms=list(name_index.keys()))
cats = coco.loadCats(catIds)
id_index = dict((cat['id'], name_index[cat['name']]) for cat in cats)
imgIds = coco.getImgIds()
path = os.path.join(root, name)
imgs = coco.loadImgs(imgIds)
_imgs = list(filter(lambda img: os.path.exists(os.path.join(path, img['file_name'])), imgs))
if len(imgs) > len(_imgs):
tf.logging.warn('%d of %d images not exists' % (len(imgs) - len(_imgs), len(imgs)))
cnt_noobj = 0
for img in tqdm.tqdm(_imgs):
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
if len(anns) <= 0:
cnt_noobj += 1
continue
imagepath = os.path.join(path, img['file_name'])
width, height = img['width'], img['height']
imageshape = [height, width, 3]
objects_class = np.array([id_index[ann['category_id']] for ann in anns], dtype=np.int64)
objects_coord = [ann['bbox'] for ann in anns]
objects_coord = [(x, y, x + w, y + h) for x, y, w, h in objects_coord]
objects_coord = np.array(objects_coord, dtype=np.float32)
if verify:
if not verify_coords(objects_coord, imageshape):
tf.logging.error('failed to verify coordinates of ' + imagepath)
continue
if not verify_image_jpeg(imagepath, imageshape):
tf.logging.error('failed to decode ' + imagepath)
continue
assert len(objects_class) == len(objects_coord)
example = tf.train.Example(features=tf.train.Features(feature={
'imagepath': tf.train.Feature(bytes_list=tf.train.BytesList(value=[tf.compat.as_bytes(imagepath)])),
'imageshape': tf.train.Feature(int64_list=tf.train.Int64List(value=imageshape)),
'objects': tf.train.Feature(bytes_list=tf.train.BytesList(value=[objects_class.tostring(), objects_coord.tostring()])),
}))
writer.write(example.SerializeToString())
if cnt_noobj > 0:
tf.logging.warn('%d of %d images have no object' % (cnt_noobj, len(_imgs)))
return True