当前位置: 首页>>代码示例>>Python>>正文


Python coco.getImgIds方法代码示例

本文整理汇总了Python中pycocotools.coco.getImgIds方法的典型用法代码示例。如果您正苦于以下问题:Python coco.getImgIds方法的具体用法?Python coco.getImgIds怎么用?Python coco.getImgIds使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pycocotools.coco的用法示例。


在下文中一共展示了coco.getImgIds方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cache

# 需要导入模块: from pycocotools import coco [as 别名]
# 或者: from pycocotools.coco import getImgIds [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 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:52,代码来源:coco.py

示例2: coco

# 需要导入模块: from pycocotools import coco [as 别名]
# 或者: from pycocotools.coco import getImgIds [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 
开发者ID:ruiminshen,项目名称:yolo-tf,代码行数:52,代码来源:cache.py


注:本文中的pycocotools.coco.getImgIds方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。