提取coco数据集person的图片和标签脚本
时间: 2023-07-09 11:09:27 浏览: 159
coco128数据集图片及标签.zip
5星 · 资源好评率100%
以下是提取coco数据集中person类别的图片和标签的Python脚本:
```python
import json
import os
import shutil
from pycocotools.coco import COCO
dataDir = 'path/to/coco/dataset'
dataType = 'train2017'
annFile = '{}/annotations/instances_{}.json'.format(dataDir, dataType)
saveDir = 'path/to/save/person/images'
saveAnnFile = 'path/to/save/person/annotations.json'
# Initialize COCO api for instance annotations
coco = COCO(annFile)
# Get category id for 'person'
catIds = coco.getCatIds(catNms=['person'])
# Get image ids for images containing 'person' category
imgIds = coco.getImgIds(catIds=catIds)
# Create directories to save person images and annotations
if not os.path.exists(saveDir):
os.makedirs(saveDir)
# Copy person images to the save directory
for imgId in imgIds:
imgInfo = coco.loadImgs(ids=imgId)[0]
imgPath = '{}/{}/{}'.format(dataDir, dataType, imgInfo['file_name'])
shutil.copy(imgPath, saveDir)
# Save person annotations to a new json file
personAnn = {'images': [], 'annotations': []}
for imgId in imgIds:
annIds = coco.getAnnIds(imgIds=imgId, catIds=catIds, iscrowd=None)
if len(annIds) == 0:
continue
imgInfo = coco.loadImgs(ids=imgId)[0]
annInfo = coco.loadAnns(ids=annIds)
personAnn['images'].append(imgInfo)
personAnn['annotations'].extend(annInfo)
with open(saveAnnFile, 'w') as f:
json.dump(personAnn, f)
```
在运行脚本之前,请确保已经安装了pycocotools库。
阅读全文