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


Python COCO.loadCats方法代码示例

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


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

示例1: main

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
def main(argv):
	## Parsing the command	
	in_path = ''
	out_path = ''
	ann_path = ''
	try:
		opts, args = getopt.getopt(argv,"hi:o:a:",["in=","out=","annotation="])
	except getopt.GetoptError:
		print 'test.py -i <inputfile> -o <outputfile> -a <annotationfile>'
		sys.exit(2)
	for opt, arg in opts:
		if opt == '-h':
			print 'test.py -i <inputfile> -o <outputfile> -a <annotationfile>'
			sys.exit()
		elif opt in ("-i", "--in"):
			in_path = arg
		elif opt in ("-o", "--out"):
			out_path = arg
		elif opt in ("-a", "--annotation"):
			ann_path = arg
	print('Performing evaluation using Coco Python API...')
	_COCO = COCO(ann_path)
	_cats = _COCO.loadCats(_COCO.getCatIds())
	_classes = tuple(['__background__'] + [c['name'] for c in _cats])
	_do_eval(in_path,out_path, _COCO, _classes)
开发者ID:879229395,项目名称:fast-rcnn-torch,代码行数:27,代码来源:evaluate_coco.py

示例2: load_coco

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
    def load_coco(self, dataset_dir, subset, class_ids=None,
                  class_map=None, return_coco=False):
        """Load a subset of the COCO dataset.
        dataset_dir: The root directory of the COCO dataset.
        subset: What to load (train, val, minival, val35k)
        class_ids: If provided, only loads images that have the given classes.
        class_map: TODO: Not implemented yet. Supports maping classes from
            different datasets to the same class ID.
        return_coco: If True, returns the COCO object.
        """
        # Path
        image_dir = os.path.join(dataset_dir, "train2014" if subset == "train"
                                 else "val2014")

        # Create COCO object
        json_path_dict = {
            "train": "annotations/instances_train2014.json",
            "val": "annotations/instances_val2014.json",
            "minival": "annotations/instances_minival2014.json",
            "val35k": "annotations/instances_valminusminival2014.json",
        }
        coco = COCO(os.path.join(dataset_dir, json_path_dict[subset]))

        # Load all classes or a subset?
        if not class_ids:
            # All classes
            class_ids = sorted(coco.getCatIds())

        # All images or a subset?
        if class_ids:
            image_ids = []
            for id in class_ids:
                image_ids.extend(list(coco.getImgIds(catIds=[id])))
            # Remove duplicates
            image_ids = list(set(image_ids))
        else:
            # All images
            image_ids = list(coco.imgs.keys())

        # Add classes
        for i in class_ids:
            self.add_class("coco", i, coco.loadCats(i)[0]["name"])

        # Add images
        for i in image_ids:
            self.add_image(
                "coco", image_id=i,
                path=os.path.join(image_dir, coco.imgs[i]['file_name']),
                width=coco.imgs[i]["width"],
                height=coco.imgs[i]["height"],
                annotations=coco.loadAnns(coco.getAnnIds(
                    imgIds=[i], catIds=class_ids, iscrowd=None)))
        if return_coco:
            return coco
开发者ID:huanglizhi,项目名称:Pytorch_Mask_RCNN,代码行数:56,代码来源:data_center.py

示例3: _load_gt_roidb

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
    def _load_gt_roidb(self):
        _coco = COCO(self._anno_file)
        # deal with class names
        cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())]
        class_to_coco_ind = dict(zip(cats, _coco.getCatIds()))
        class_to_ind = dict(zip(self.classes, range(self.num_classes)))
        coco_ind_to_class_ind = dict([(class_to_coco_ind[cls], class_to_ind[cls])
                                     for cls in self.classes[1:]])

        image_ids = _coco.getImgIds()
        gt_roidb = [self._load_annotation(_coco, coco_ind_to_class_ind, index) for index in image_ids]
        return gt_roidb
开发者ID:dpom,项目名称:incubator-mxnet,代码行数:14,代码来源:coco.py

示例4: load_coco

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
    def load_coco(self, dataset_dir, subset, year=DEFAULT_DATASET_YEAR, class_ids=None,
                  class_map=None, return_coco=False, auto_download=False):
        """Load a subset of the COCO dataset.
        dataset_dir: The root directory of the COCO dataset.
        subset: What to load (train, val, minival, valminusminival)
        year: What dataset year to load (2014, 2017) as a string, not an integer
        class_ids: If provided, only loads images that have the given classes.
        class_map: TODO: Not implemented yet. Supports maping classes from
            different datasets to the same class ID.
        return_coco: If True, returns the COCO object.
        auto_download: Automatically download and unzip MS-COCO images and annotations
        """

        if auto_download is True:
            self.auto_download(dataset_dir, subset, year)

        coco = COCO("{}/annotations/instances_{}{}.json".format(dataset_dir, subset, year))
        if subset == "minival" or subset == "valminusminival":
            subset = "val"
        image_dir = "{}/{}{}".format(dataset_dir, subset, year)

        # Load all classes or a subset?
        if not class_ids:
            # All classes
            class_ids = sorted(coco.getCatIds())

        # All images or a subset?
        if class_ids:
            image_ids = []
            for id in class_ids:
                image_ids.extend(list(coco.getImgIds(catIds=[id])))
            # Remove duplicates
            image_ids = list(set(image_ids))
        else:
            # All images
            image_ids = list(coco.imgs.keys())

        # Add classes
        for i in class_ids:
            self.add_class("coco", i, coco.loadCats(i)[0]["name"])

        # Add images
        for i in image_ids:
            self.add_image(
                "coco", image_id=i,
                path=os.path.join(image_dir, coco.imgs[i]['file_name']),
                width=coco.imgs[i]["width"],
                height=coco.imgs[i]["height"],
                annotations=coco.loadAnns(coco.getAnnIds(
                    imgIds=[i], catIds=class_ids, iscrowd=None)))
        if return_coco:
            return coco
开发者ID:RubensZimbres,项目名称:Mask_RCNN,代码行数:54,代码来源:coco.py

示例5: Resize_Image

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [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]))
开发者ID:SnowMasaya,项目名称:Chainer_Image_Caption_code,代码行数:50,代码来源:resize_image.py

示例6: main

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [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))
开发者ID:caomw,项目名称:coco-dpm,代码行数:49,代码来源:convert_to_pascalformat.py

示例7: LoadImageList

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [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
开发者ID:gnoses,项目名称:CaffeExample,代码行数:23,代码来源:MSCOCO_CreateDB.py

示例8: _load_jsons

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [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
开发者ID:mohamedelsiesyibra,项目名称:gluon-cv,代码行数:42,代码来源:instance.py

示例9: coco2kitti

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
def coco2kitti(catNms, annFile):

    # initialize COCO api for instance annotations
    coco = COCO(annFile)

    # Create an index for the category names
    cats = coco.loadCats(coco.getCatIds())
    cat_idx = {}
    for c in cats:
        cat_idx[c['id']] = c['name']

    for img in coco.imgs:

        # Get all annotation IDs for the image
        catIds = coco.getCatIds(catNms=catNms)
        annIds = coco.getAnnIds(imgIds=[img], catIds=catIds)

        # If there are annotations, create a label file
        if len(annIds) > 0:
            # Get image filename
            img_fname = coco.imgs[img]['file_name']
            # open text file
            with open('./labels/' + img_fname.split('.')[0] + '.txt','w') as label_file:
                anns = coco.loadAnns(annIds)
                for a in anns:
                    bbox = a['bbox']
                    # Convert COCO bbox coords to Kitti ones
                    bbox = [bbox[0], bbox[1], bbox[2] + bbox[0], bbox[3] + bbox[1]]
                    bbox = [str(b) for b in bbox]
                    catname = cat_idx[a['category_id']]
                    # Format line in label file
                    # Note: all whitespace will be removed from class names
                    out_str = [catname.replace(" ","")
                               + ' ' + ' '.join(['0']*3)
                               + ' ' + ' '.join([b for b in bbox])
                               + ' ' + ' '.join(['0']*8)
                               +'\n']
                    label_file.write(out_str[0])
开发者ID:XJTUeducation,项目名称:jetson-inference,代码行数:40,代码来源:coco2kitti.py

示例10: coco

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
class coco(imdb):
  def __init__(self, image_set, year):
    imdb.__init__(self, 'coco_' + year + '_' + image_set)
    # COCO specific config options
    self.config = {'use_salt': True,
                   'cleanup': True}
    # name, paths
    self._year = year
    self._image_set = image_set
    self._data_path = osp.join(cfg.DATA_DIR, 'coco')
    # load COCO API, classes, class <-> id mappings
    self._COCO = COCO(self._get_ann_file())
    cats = self._COCO.loadCats(self._COCO.getCatIds())
    self._classes = tuple(['__background__'] + [c['name'] for c in cats])
    self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes)))))
    self._class_to_coco_cat_id = dict(list(zip([c['name'] for c in cats],
                                               self._COCO.getCatIds())))
    self._image_index = self._load_image_set_index()
    # Default to roidb handler
    self.set_proposal_method('gt')
    self.competition_mode(False)

    # Some image sets are "views" (i.e. subsets) into others.
    # For example, minival2014 is a random 5000 image subset of val2014.
    # This mapping tells us where the view's images and proposals come from.
    self._view_map = {
      'minival2014': 'val2014',  # 5k val2014 subset
      'valminusminival2014': 'val2014',  # val2014 \setminus minival2014
      'test-dev2015': 'test2015',
    }
    coco_name = image_set + year  # e.g., "val2014"
    self._data_name = (self._view_map[coco_name]
                       if coco_name in self._view_map
                       else coco_name)
    # Dataset splits that have ground-truth annotations (test splits
    # do not have gt annotations)
    self._gt_splits = ('train', 'val', 'minival')

  def _get_ann_file(self):
    prefix = 'instances' if self._image_set.find('test') == -1 \
      else 'image_info'
    return osp.join(self._data_path, 'annotations',
                    prefix + '_' + self._image_set + self._year + '.json')

  def _load_image_set_index(self):
    """
    Load image ids.
    """
    image_ids = self._COCO.getImgIds()
    return image_ids

  def _get_widths(self):
    anns = self._COCO.loadImgs(self._image_index)
    widths = [ann['width'] for ann in anns]
    return widths

  def image_path_at(self, i):
    """
    Return the absolute path to image i in the image sequence.
    """
    return self.image_path_from_index(self._image_index[i])

  def image_path_from_index(self, index):
    """
    Construct an image path from the image's "index" identifier.
    """
    # Example image path for index=119993:
    #   images/train2014/COCO_train2014_000000119993.jpg
    file_name = ('COCO_' + self._data_name + '_' +
                 str(index).zfill(12) + '.jpg')
    image_path = osp.join(self._data_path, 'images',
                          self._data_name, file_name)
    assert osp.exists(image_path), \
      'Path does not exist: {}'.format(image_path)
    return image_path

  def gt_roidb(self):
    """
    Return the database of ground-truth regions of interest.
    This function loads/saves from/to a cache file to speed up future calls.
    """
    cache_file = osp.join(self.cache_path, self.name + '_gt_roidb.pkl')
    if osp.exists(cache_file):
      with open(cache_file, 'rb') as fid:
        roidb = pickle.load(fid)
      print('{} gt roidb loaded from {}'.format(self.name, cache_file))
      return roidb

    gt_roidb = [self._load_coco_annotation(index)
                for index in self._image_index]

    with open(cache_file, 'wb') as fid:
      pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL)
    print('wrote gt roidb to {}'.format(cache_file))
    return gt_roidb

  def _load_coco_annotation(self, index):
    """
    Loads COCO bounding-box instance annotations. Crowd instances are
    handled by marking their overlaps (with all categories) to -1. This
#.........这里部分代码省略.........
开发者ID:StanislawAntol,项目名称:tf-faster-rcnn,代码行数:103,代码来源:coco.py

示例11: load_coco

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
    def load_coco(self, dataset_dir, subset, year=DEFAULT_DATASET_YEAR, class_ids=None,
                  class_map=None, return_coco=False, auto_download=False):
        """Load a subset of the COCO dataset.
        dataset_dir: The root directory of the COCO dataset.
        subset: What to load (train, val, minival, valminusminival)
        year: What dataset year to load (2014, 2017) as a string, not an integer
        class_ids: If provided, only loads images that have the given classes.
        class_map: TODO: Not implemented yet. Supports maping classes from
            different datasets to the same class ID.
        return_coco: If True, returns the COCO object.
        auto_download: Automatically download and unzip MS-COCO images and annotations
        """

        if auto_download is True:
            self.auto_download(dataset_dir, subset, year)


        coco = COCO("{}/annotations/{}_{}{}.json".format(dataset_dir, self.task_type, subset, year))
        if subset == "minival" or subset == "valminusminival":
            subset = "val"
        image_dir = "{}/{}{}".format(dataset_dir, subset, year)

        # Load all classes or a subset?
        if not class_ids:
            # All classes
            class_ids = sorted(coco.getCatIds())
            # print(class_ids)

        # All images or a subset?
        if class_ids:
            image_ids = []
            for id in class_ids:
                image_ids.extend(list(coco.getImgIds(catIds=[id])))
            # Remove duplicates
            image_ids = list(set(image_ids))
        else:
            # All images
            image_ids = list(coco.imgs.keys())

        # Add classes
        for i in class_ids:
            self.add_class("coco", i, coco.loadCats(i)[0]["name"])

        # Add images
        for i in image_ids:
            self.add_image(
                "coco", image_id=i,
                path=os.path.join(image_dir, coco.imgs[i]['file_name']),
                width=coco.imgs[i]["width"],
                height=coco.imgs[i]["height"],
                annotations=coco.loadAnns(coco.getAnnIds(
                    imgIds=[i], catIds=class_ids, iscrowd=None)))

        if(self.task_type == "person_keypoints"):
            #the connection between 2 close keypoints
            self._skeleton = coco.loadCats(Person_ID)[0]["skeleton"]
            #keypoint names
            # ["nose","left_eye","right_eye","left_ear","right_ear","left_shoulder",
            # "right_shoulder","left_elbow","right_elbow","left_wrist","right_wrist",
            # "left_hip","right_hip","left_knee","right_knee","left_ankle","right_ankle"]
            self._keypoint_names = coco.loadCats(Person_ID)[0]["keypoints"]

            self._skeleton = np.array(self._skeleton,dtype=np.int32)

            print("Skeleton:",np.shape(self._skeleton))
            print("Keypoint names:",np.shape(self._keypoint_names))
        if return_coco:
            return coco
开发者ID:PanZiqiAI,项目名称:FashionAI_Key_Points_Detection,代码行数:70,代码来源:coco.py

示例12: __init__

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
class Loader:
    def __init__(self, train=True):
        if train:
            self.image_dir = train_dir
            ann_file = train_ann_file
            self.get_image_path = self.get_train_path
        else:
            self.image_dir = val_dir
            ann_file = val_ann_file
            self.get_image_path = self.get_val_path

        self.coco = COCO(ann_file)
        cats = self.coco.loadCats(self.coco.getCatIds())
        names = [cat['name'] for cat in cats]
        # id is number from pycocotools
        # i is actual index used
        id2name = dict((cat["id"], cat["name"]) for cat in cats)
        self.id2i = dict((cats[i]['id'], i) for i in range(len(cats)))
        self.i2name = {v: id2name[k] for k, v in self.id2i.items()}
        self.i2name[classNum] = "void"

        print("NUMBER OF CLASSES: %i" % len(id2name))

        self.cat_ids = self.coco.getCatIds()
        self.img_ids = self.coco.getImgIds()

        print("%i total training images" % len(self.img_ids))

    def preprocess_batch(self, batch, augment=True):
        imgs = []
        all_used_anns = []

        for img, anns in batch:
            used_anns = []
            w = img.shape[1]
            h = img.shape[0]

            option = np.random.randint(2)

            if not augment:
                option = 0

            if option == 0:
                sample = img
            elif option == 1:
                ratio = random.uniform(0.5, 2.0) #  0.5=portrait, 2.0=landscape
                scale = random.uniform(0.1, 1.0)

                if w > h:
                    p_w = w * scale
                    p_h = p_w / ratio

                    if p_w > w or p_h > h:
                        p_h = h * scale
                        p_w = p_h * ratio
                else:
                    p_h = h * scale
                    p_w = p_h * ratio

                    if p_w > w or p_h > h:
                        p_w = w * scale
                        p_h = p_w / ratio

                if p_w > w or p_h > h:
                    print("error: patch is too big.")

                p_x = random.uniform(0, w - p_w)
                p_y = random.uniform(0, h - p_h)

                sample = img[int(p_y):int(p_y + p_h), int(p_x):int(p_x + p_w)]

                for box, id in anns:
                    box[0] -= p_x
                    box[1] -= p_y

            # warning: this function turns 255 -> 1.0
            resized_img = skimage.transform.resize(sample, (inputSize, inputSize), mode = "constant")

            for box, id in anns:
                scaleX = 1.0 / float(sample.shape[1])
                scaleY = 1.0 / float(sample.shape[0])

                box[0] *= scaleX
                box[1] *= scaleY
                box[2] *= scaleX
                box[3] *= scaleY

            for box, id in anns: # only use boxes with center in image
                cX = box[0] + box[2] / 2.0
                cY = box[1] + box[3] / 2.0

                if cX >= 0 and cX <= 1 and cY >= 0 and cY <= 1:
                    used_anns.append((box, id))

            if random.uniform(0.0, 1.0) < 0.5:
                resized_img = np.fliplr(resized_img)

                for box, id in used_anns:
                    box[0] = 1.0 - box[0] - box[2]

#.........这里部分代码省略.........
开发者ID:wuyx,项目名称:SSDNet-Tensorflow,代码行数:103,代码来源:cocoTools.py

示例13: open

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
import pdb
pylab.rcParams['figure.figsize'] = (10.0,8.0)

dataDir='..'
dataType='val2014'
#dataType='train2014'

saveImgPath = '%s/JPEGImages/' %(dataDir)
saveAnnoPath = '%s/Annotations/'%(dataDir)
annFile='%s/annotations/instances_%s.json'%(dataDir,dataType)
coco=COCO(annFile)

listOut = open('%s/ImageSets/Main/%sIndoor.txt'%(dataDir, dataType), 'w')
indoorCatIds = [62, 63, 67, 72, 78, 82]
# display category information
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]
开发者ID:GoYchen,项目名称:programs,代码行数:33,代码来源:getCOCOlabel.py

示例14: COCO

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
trainAnnFile = '%s/annotations/instances_%s.json'%(dataDir, trainDataType)

#valDataType = 'val2014'
#valAnnFile = '%s/annotations/instances_%s.json'%(dataDir, valDataType)

# NO annotations for test set
#testDataType = 'test2014'
#testAnnFile = '%s/annotations/instance_%s.json'%(dataDir, testDataType)


# initialize COCO API for instance annotations
train = COCO(trainAnnFile)
#val = COCO(valAnnFile)
#test = COCO(testAnnFile)

cats = train.loadCats(train.getCatIds())
nms = [cat['name'] for cat in cats]
print 'COCO train categories:\n\n', ' '.join(nms)

# here we need set() to eliminate the repeated supercategories, since
# many categories may have the same supercategory
nms = set([cat['supercategory'] for cat in cats]) #test=[cat['supercategory'] for cat in cats]
print 'COCO supercategoires :\n', ' '.join(nms)

# get all images of some given category
catIds = train.getCatIds(catNms=['person', 'dog', 'skateboard'])
imgIds = train.getImgIds(catIds=catIds)

# load and display image
for i in range(0, 5):
	img = train.loadImgs(imgIds[np.random.randint(0, len(imgIds))])[0]
开发者ID:DeercoderResearch,项目名称:coco-1,代码行数:33,代码来源:learn1.py

示例15:

# 需要导入模块: from pycocotools.coco import COCO [as 别名]
# 或者: from pycocotools.coco.COCO import loadCats [as 别名]
import torch.nn as nn

from math import ceil, floor 


# ### Load Data

# In[17]:


dataType = 'train2014'
dataDir='' 
annFile_train='instances_{}.json'.format(dataType)
coco_train=COCO(annFile_train)

cats = coco_train.loadCats(coco_train.getCatIds()) # categories
cat_id_to_name = {cat['id']: cat['name'] for cat in cats} # category id to name mapping
cat_name_to_id = {cat['name']: cat['id'] for cat in cats} # category name to id mapping

cat_to_supercat = {cat['name']: cat['supercategory'] for cat in cats}
cat_id_to_supercat = {cat['id']: cat['supercategory'] for cat in cats}


# In[18]:


## Validation
dataType = 'val2014'
dataDir='' 
annFile_val='instances_{}.json'.format(dataType)
coco_val=COCO(annFile_val)
开发者ID:EmilyYanW,项目名称:Machine_Learning,代码行数:33,代码来源:8.Computer_Vision_Image_Detection_and_Retrieval.py


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