Py의 pycocotools: pycocotools 라이브러리, 설치 및 사용법에 대한 자세한 소개
콘텐츠
1、pycocotools.coco에서 COCO 가져오기
pycocotools 라이브러리 소개
pycocotools 란 무엇입니까? 즉 COCO의 python api 도구. COCO는 객체 감지, 분할, 인간 키포인트 감지, 재료 분할 및 캡션 생성을 위한 대규모 이미지 데이터 세트입니다. 이 패키지는 COCO에서 주석 로드, 구문 분석 및 시각화를 용이하게 하는 Matlab, Python 및 lua API를 제공합니다. 데이터, 논문 및 자습서를 포함하여 COCO에 대해 자세히 알아보려면 COCO - 컨텍스트의 공통 개체를 방문하십시오 . 주석의 정확한 형식은 COCO 웹사이트에도 설명되어 있습니다. Matlab 및 Python API가 완료되었으며 Lua API는 기본 기능만 제공합니다.
이 API 외에도 데모를 실행하고 API를 사용하려면 COCO 이미지와 메모를 다운로드하십시오. 둘 다 프로젝트 웹 사이트에서 찾을 수 있습니다.
- - 다운로드하여 압축을 풀고 이미지를 coco/images/에 넣으십시오.
- - 주석을 다운로드하여 다음 위치에 배치하십시오: coco/annotations/
코코 API: http://cocodataset.org/
pycocotools 라이브러리 설치
pip install pycocotools==2.0.0
pycocotools 라이브러리를 사용하는 방법
1、pycocotools.coco에서 COCO 가져오기
__author__ = 'tylin'
__version__ = '2.0'
# Interface for accessing the Microsoft COCO dataset.
# Microsoft COCO is a large image dataset designed for object detection,
# segmentation, and caption generation. pycocotools is a Python API that
# assists in loading, parsing and visualizing the annotations in COCO.
# Please visit http://mscoco.org/ for more information on COCO, including
# for the data, paper, and tutorials. The exact format of the annotations
# is also described on the COCO website. For example usage of the pycocotools
# please see pycocotools_demo.ipynb. In addition to this API, please download both
# the COCO images and annotations in order to run the demo.
# An alternative to using the API is to load the annotations directly
# into Python dictionary
# Using the API provides additional utility functions. Note that this API
# supports both *instance* and *caption* annotations. In the case of
# captions not all functions are defined (e.g. categories are undefined).
# The following API functions are defined:
# COCO - COCO api class that loads COCO annotation file and prepare data structures.
# decodeMask - Decode binary mask M encoded via run-length encoding.
# encodeMask - Encode binary mask M using run-length encoding.
# getAnnIds - Get ann ids that satisfy given filter conditions.
# getCatIds - Get cat ids that satisfy given filter conditions.
# getImgIds - Get img ids that satisfy given filter conditions.
# loadAnns - Load anns with the specified ids.
# loadCats - Load cats with the specified ids.
# loadImgs - Load imgs with the specified ids.
# annToMask - Convert segmentation in an annotation to binary mask.
# showAnns - Display the specified annotations.
# loadRes - Load algorithm results and create API for accessing them.
# download - Download COCO images from mscoco.org server.
# Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
# Help on each functions can be accessed by: "help COCO>function".
# See also COCO>decodeMask,
# COCO>encodeMask, COCO>getAnnIds, COCO>getCatIds,
# COCO>getImgIds, COCO>loadAnns, COCO>loadCats,
# COCO>loadImgs, COCO>annToMask, COCO>showAnns
# Microsoft COCO Toolbox. version 2.0
# Data, paper, and tutorials available at: http://mscoco.org/
# Code written by Piotr Dollar and Tsung-Yi Lin, 2014.
# Licensed under the Simplified BSD License [see bsd.txt]
2. COCO 데이터셋 정보 출력 및 이미지 시각화
from pycocotools.coco import COCO
import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import random
#1、定义数据集路径
cocoRoot = "F:/File_Python/Resources/image/COCO"
dataType = "val2017"
annFile = os.path.join(cocoRoot, f'annotations/instances_{dataType}.json')
print(f'Annotation file: {annFile}')
#2、为实例注释初始化COCO的API
coco=COCO(annFile)
#3、采用不同函数获取对应数据或类别
ids = coco.getCatIds('person')[0] #采用getCatIds函数获取"person"类别对应的ID
print(f'"person" 对应的序号: {ids}')
id = coco.getCatIds(['dog'])[0] #获取某一类的所有图片,比如获取包含dog的所有图片
imgIds = coco.catToImgs[id]
print(f'包含dog的图片共有:{len(imgIds)}张, 分别是:',imgIds)
cats = coco.loadCats(1) #采用loadCats函数获取序号对应的类别名称
print(f'"1" 对应的类别名称: {cats}')
imgIds = coco.getImgIds(catIds=[1]) #采用getImgIds函数获取满足特定条件的图片(交集),获取包含person的所有图片
print(f'包含person的图片共有:{len(imgIds)}张')
#4、将图片进行可视化
imgId = imgIds[10]
imgInfo = coco.loadImgs(imgId)[0]
print(f'图像{imgId}的信息如下:\n{imgInfo}')
imPath = os.path.join(cocoRoot, 'images', dataType, imgInfo['file_name'])
im = cv2.imread(imPath)
plt.axis('off')
plt.imshow(im)
plt.show()
plt.imshow(im); plt.axis('off')
annIds = coco.getAnnIds(imgIds=imgInfo['id']) # 获取该图像对应的anns的Id
print(f'图像{imgInfo["id"]}包含{len(anns)}个ann对象,分别是:\n{annIds}')
anns = coco.loadAnns(annIds)
coco.showAnns(anns)
print(f'ann{annIds[3]}对应的mask如下:')
mask = coco.annToMask(anns[3])
plt.imshow(mask); plt.axis('off')