當前位置: 首頁>>代碼示例>>Python>>正文


Python coco.loadCats方法代碼示例

本文整理匯總了Python中pycocotools.coco.loadCats方法的典型用法代碼示例。如果您正苦於以下問題:Python coco.loadCats方法的具體用法?Python coco.loadCats怎麽用?Python coco.loadCats使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pycocotools.coco的用法示例。


在下文中一共展示了coco.loadCats方法的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: cache

# 需要導入模塊: from pycocotools import coco [as 別名]
# 或者: from pycocotools.coco import loadCats [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 loadCats [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.loadCats方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。