如何下载 COCO 数据集图像?

数据挖掘 Python
2022-02-28 20:39:54

我正在尝试使用以下 COCO API 命令下载 COCO 数据集图像:

from pycocotools.coco import COCO
import requests
catIds = COCO.getCatIds(catNms=['person','dog', 'car'])

...但我收到以下错误消息。知道为什么会这样吗?

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-9cc4e2f62a0e> in <module>
----> 1 catIds = COCO.getCatIds(catNms=['person','dog', 'car'])

TypeError: getCatIds() missing 1 required positional argument: 'self'

以前,我使用这些说明配置了 pycocotools

编辑:

还有一些奇怪的错误信息。查看代码似乎没有“人”、“狗”或“汽车”这样的类别。为什么会这样?

我的代码:

a = COCO()  
catIds = a.getCatIds(catNms=['person','dog', 'car'])

收到错误信息:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-12-57400207fde1> in <module>
      1 a = COCO() # calling init
----> 2 catIds = a.getCatIds(catNms=['person','dog', 'car'])

~\Anaconda3\lib\site-packages\pycocotools\coco.py in getCatIds(self, catNms, supNms, catIds)
    171             cats = self.dataset['categories']
    172         else:
--> 173             cats = self.dataset['categories']
    174             cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name']          in catNms]
    175             cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]

KeyError: 'categories'

从文件'cocoapi/PythonAPI/pycocotools/coco.py'中提取: 在此处输入图像描述

2个回答

COCO 是一个 Python 类,而 getCatIds 不是静态方法,只能由 COCO 类的实例/对象调用,而不能从类本身调用。

您可能可以通过这样做来解决它:

a = COCO() # calling init
catIds = a.getCatIds(catNms=['person','dog', 'car']) # calling the method from the class

(基于从https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/coco.py读取代码的答案)

根据这里的演示代码,您必须单独下载数据,然后使用pycocotools包来访问数据:

from pycocotools.coco import COCO

# After downloading images from http://cocodataset.org/#download

# Define location of annotations
dataDir = '..'
dataType = 'val2017'
annFile = f'{dataDir}/annotations/instances_{dataType}.json'

# Create instance
coco = COCO(annFile)

# Filter for specific categories 
catIds = coco.getCatIds(catNms=['person','dog', 'car'])