AI Logic

Datasets and Benchmarks

COCO

Updated:

How COCO was built and its annotation types. Left: the flow of collecting Flickr photos by combinations of objects, answering which categories appear, finding objects one by one, and drawing outlines to build COCO, then splitting it into the 2017 training, validation, and test sets. Right: the formats of the box, mask, keypoints, and caption attached to a photo, and the AP evaluation rules

Overview

COCO (Microsoft Common Objects in Context) is a dataset of photos of everyday objects in natural scenes, with per-object boxes and outlines (masks) added by hand. It was published by Lin et al. in 2014. It is used as the standard data for comparing performance in object detection, instance segmentation (separating each object at the pixel level), human keypoint detection, and image caption generation.

The goal was to bring object recognition closer to "scene understanding." The paper names three challenges for this.

  • Non-iconic views: recognizing objects that are occluded or small, rather than photos like top image-search results where the object appears large in the center
  • Contextual reasoning between objects: using surrounding objects as cues to recognize small or ambiguous objects
  • Precise localization: indicating object positions with pixel-level outlines, finer than boxes

It contains 91 categories, 328,000 images, and 2.5 million objects. Each image shows on average 3.5 categories and 7.7 objects, more than the ImageNet detection data (3.0) and PASCAL VOC (2.3) by the paper's comparison.

"AP on COCO" in papers is usually the value averaged over 80 categories and over 10 IoU thresholds from 0.50 to 0.95. Its definition differs from PASCAL VOC's mAP (IoU 0.5 only), and the same model scores considerably lower on it.

Contents: construction, categories, splits, and format

COCO was built through the following steps.

  1. Choose the categories. 272 candidates were compiled from PASCAL VOC categories, frequently used object names, and objects that children aged 4–8 named around them, and the authors narrowed them to 91 by vote. Only objects (things) with everyday names that even a 4-year-old understands, such as "dog" or "chair," were chosen; things without clear boundaries (stuff), such as sky, road, or grass, were left out. All 20 VOC categories are included.
  2. Collect photos. Photos were gathered from Flickr by searching not for one category at a time but for pairs of categories, such as "dog + car," or combinations of scenes and objects. Searching for a single word yields mostly iconic photos with the object large in the center.
  3. Label which categories appear. Workers on Amazon Mechanical Turk (a service for outsourcing tasks online) answered whether each of 11 supercategories, such as animals or vehicles, is present, and if so placed an icon on that object. Each image is seen by 8 workers to reduce misses.
  4. Spot objects one by one. For each category, every object present is marked (up to 10 per image). This is also done by 8 workers.
  5. Draw outlines. Workers who passed a training task (about 1 in 3) drew an outline for each object. Each outline was checked by 3–5 workers, and poor ones were redrawn. When there were more than 10–15 objects of the same category (crowds, piles of bananas, and so on), the rest were grouped into a single "crowd" region.

According to the paper, workers spent more than 70,000 hours in total. Drawing outlines alone took over 22 hours per 1,000 objects.

Each image also has five English captions. Human keypoints, stuff regions, and panoptic annotations (a task that labels every pixel with things and stuff combined) were added later.

There are two splits, the 2014 and 2017 versions. Both re-split the same images; no new images or detection annotations were added.

VersionTrainingValidationTest (labels not public)
201482,783 images40,504 images40,775 images (used for the caption task)
2017About 118,000 images5,000 images40,670 images (including 20,288 test-dev)

Based on user feedback, the 2017 version shrank the validation set to 5,000 images and moved the rest to training. Even before that, it was common practice to add 35,000 of the 2014 validation images to training and evaluate on the remaining 5,000 (called minival). Object annotations (boxes and masks) exist for 80 categories. Of the 91, the 11 categories hat, shoe, eyeglasses, mirror, window, door, street sign, plate, desk, blender, and hair brush were not given masks, because they were too numerous, ambiguous, easily confused with other categories, or too rare.

The format is one JSON file per split. It contains images (image ID, size, file name, license number), annotations (the list of annotations), categories (category ID, name, supercategory), and licenses. Each object annotation has the following fields.

FieldContents
bboxBox. [x, y, width, height] (top-left corner coordinates and size, in pixels)
segmentationMask. Polygons for a single object (multiple when split by occlusion); RLE (a compressed format representing pixels by run lengths of the same value) for crowds
iscrowd1 for a crowd region, 0 for a single object
areaMask area (number of pixels)
category_idCategory ID. In the range 1–90, with some unused numbers
keypointsPeople only. 17 points as a sequence of [x, y, v]. v is 0 for not labeled, 1 for labeled but occluded, 2 for visible

A caption annotation is a pair of an image ID and a caption (one English sentence).

Evaluation protocol

Object detection and instance segmentation use AP (Average Precision). The computation follows the same flow as mAP: for each category, predictions are sorted by confidence and AP is obtained from the precision-recall curve. The COCO rules are as follows.

  1. The overlap between prediction and ground truth is measured by IoU. For the box task it is box IoU, for the mask task mask IoU; the rest of the computation is exactly the same.
  2. The IoU threshold is varied over 10 values, 0.50, 0.55, …, 0.95, and AP is computed for each.
  3. AP is the average of interpolated precision at 101 points of recall, 0, 0.01, …, 1.
  4. The value averaged over the 10 thresholds and 80 categories is called "AP" and is the most important metric.
AP=110∑t∈{0.50,0.55,…,0.95}180∑k=180APk,t\mathrm{AP} = \frac{1}{10}\sum_{t \in \{0.50, 0.55, \dots, 0.95\}} \frac{1}{80}\sum_{k=1}^{80} \mathrm{AP}_{k,t}

COCO's evaluation page does not distinguish AP from mAP and calls the value averaged over all categories "AP." Averaging over several thresholds is done to reward detectors with more precise localization. If a hit only requires IoU 0.5, even boxes that are roughly off can get full marks.

Besides AP, the following values are reported as well.

MetricContents
AP50, AP75AP computed at IoU 0.50 only (corresponding to the VOC criterion) and at 0.75 only (a strict criterion)
APS, APM, APLAP for small objects only (area under 32232^2 pixels), medium (32232^2 to 96296^2), and large (96296^2 and above)
AR1, AR10, AR100Maximum recall achievable with up to 1, 10, or 100 predictions per image

According to the evaluation page, about 41% of objects are small, 34% medium, and 24% large; the abundance of small objects is a hallmark of COCO. Every metric is computed using up to the 100 most confident predictions per image. Predictions that overlap crowd regions (iscrowd = 1) count as neither hits nor misses.

For keypoints, OKS (Object Keypoint Similarity) is used instead of IoU to measure how close the prediction is to the ground truth, and AP is computed in the same way. With did_i the distance between ground-truth point ii and the predicted point, ss the object scale (square root of the mask area), and κi\kappa_i a per-keypoint-type constant,

OKS=∑iexp⁡(−di2/2s2κi2) δ(vi>0)∑iδ(vi>0)\mathrm{OKS} = \frac{\sum_i \exp\left(-d_i^2 / 2 s^2 \kappa_i^2\right) \, \delta(v_i > 0)}{\sum_i \delta(v_i > 0)}

where δ(vi>0)\delta(v_i > 0) is 1 if the ground-truth point is labeled. κi\kappa_i is set from the spread when multiple workers annotate the same person; points with well-defined positions, such as eyes and nose, get smaller (stricter) values. Keypoint evaluation uses the top 20 predictions per image.

Captions are evaluated with BLEU, METEOR, ROUGE-L, and CIDEr.

The labels of the test data are not public; results are submitted to an evaluation server for scoring. Since 2017, the test set has been split into test-dev (about 20,000 images) and test-challenge (about 20,000 images). Paper results are usually reported on test-dev. Submissions to test-dev are limited to 5 per day.

Values on the validation set (val2017) and on test-dev are treated as different things. When comparing tables across papers, always make sure they match in which set the values come from and whether the AP is for boxes or masks.

Usage and historical significance

COCO is the standard benchmark for the following tasks.

  • Object detection: models such as Faster R-CNN, YOLO, SSD, FPN, and DETR are compared by COCO AP. Training techniques for detection (such as Focal Loss) also typically demonstrate their effect on COCO.
  • Instance segmentation: models that output per-object masks, such as Mask R-CNN, are compared by mask AP.
  • Human keypoint detection and image caption generation: compared by OKS-based AP and by BLEU, CIDEr, and so on, respectively.
  • Pretraining: detection models trained on COCO serve as the starting point for detection on other data (fine-tuning).

The paper showed that COCO is harder than PASCAL VOC using the same detector (DPM, a part-based detector from before deep learning). The average AP over the 20 VOC categories was as follows.

Training dataEvaluated on VOC 2012Evaluated on COCO
PASCAL VOC 201229.616.9
COCO26.819.1

The model trained on VOC had its AP roughly halved when evaluated on COCO. The model trained on COCO, on the other hand, showed a smaller gap between the two datasets (7.7 versus 12.7), and the paper suggests that "models trained on COCO generalize more easily even to easier data such as VOC."

Since then, deep learning models have raised COCO AP substantially. All values below are on test-dev.

PaperModelTaskAPAP50
Ren et al. (2015)Faster R-CNN (VGG-16)Box21.942.7
He et al. (2017)Mask R-CNN (ResNeXt-101-FPN)Box39.862.3
He et al. (2017)Mask R-CNN (ResNeXt-101-FPN)Mask37.160.0
He et al. (2017)Mask R-CNN (ResNet-50-FPN)Keypoints63.187.3

The Faster R-CNN paper also reports that its detector with ResNet-101 took first place in the COCO 2015 detection challenge. In the error analysis of this detector on the evaluation page, the AP of 0.399 at IoU 0.75 rises to 0.682 when localization errors are removed and to 0.870 when background false positives are also removed. Most errors came from imprecise localization and background false positives. Being able to probe a model's weaknesses by breaking AP down by condition in this way is another characteristic of COCO evaluation.

Practical notes

License: the annotations and the official website belong to the COCO Consortium and are released under Creative Commons Attribution 4.0 (CC BY 4.0). However, the consortium does not own the copyright of the images. The images were collected from Flickr, their use must follow Flickr's terms of use, and the terms of use state that responsibility lies with the user.

Each image carries its Flickr license number, and conditions differ per image: Attribution (BY), Attribution-NonCommercial (BY-NC), Attribution-NonCommercial-NoDerivs (BY-NC-ND), and so on. Of the 40,670 images in the 2017 test set, about 70% carry a non-commercial (NC) condition. Check the license of each image before redistributing images or using them as training data for a product. The annotations being CC BY 4.0 does not mean the images can be used freely.

Do not mix the 2014 and 2017 versions: the 2017 training and validation sets are re-splits of the same images as the 2014 training and validation sets. For example, training on train2017 and evaluating on val2014 means most of the evaluation images were seen during training. When using a pretrained model from elsewhere, also check which split of which version it was trained on.

Category IDs are not contiguous: the IDs of the 80 categories are scattered across 1–90 (because the numbers of the 11 categories without masks are missing from the 91). Build a mapping table to the model's output indices (0–79, etc.), and convert back to the original IDs when submitting to the evaluation server.

Crowds and small objects: crowd regions are merged into a single mask and ignored in evaluation. How crowd regions are handled in training (ignored or used) also changes results. And because there are many small objects, shrinking input images lowers APS considerably.

Tuning to the test data: submissions to test-dev are limited to 5 per day. Tune hyperparameters on the validation set and use test-dev for the final evaluation.

Comparison with similar datasets

Datasets commonly used for object detection, compared from the same viewpoints:

DatasetImagesNumber of categoriesObjects per imageAnnotation typesDetection evaluation
PASCAL VOC (2012)Flickr photos, 11,540 for training and validation202.3Boxes, flags such as difficult, masks for some images (per class and per object), boxes for people's heads, hands, and feet, human actionsAP (IoU 0.5) averaged over 20 classes
COCO (2017)Flickr photos, about 118,000 for training80 (object annotations)7.7Boxes, per-object masks (crowds as one region), 17 human keypoints, 5 captionsAP (10 IoU thresholds 0.50–0.95) averaged over 80 classes, AP50, AP75, by size
ImageNet (ILSVRC detection)Photos, 400,0002003.0 (validation)BoxesAP (IoU 0.5 as standard)

(The numbers of objects per image are from the COCO paper's tally.)

Rules of thumb for choosing:

  • To compare a detection or segmentation model with current research, report COCO AP (together with AP50, AP75, and AP by size).
  • To try things quickly on smaller data or compare with older papers, use PASCAL VOC mAP.
  • For pretraining on whole-image classification, use ImageNet; using those weights as the starting point for detection on COCO is the common workflow.

PyTorch example

Show code
python
import torch
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

"""
Load COCO (2017 version) with torchvision and compute the official AP with pycocotools
Download the images and annotations from the official site and place them as follows (pip install pycocotools is also needed):
  coco/val2017/                              images (000000000139.jpg, etc.)
  coco/annotations/instances_val2017.json    box and mask annotations
"""

root = 'coco/val2017'
ann_file = 'coco/annotations/instances_val2017.json'

# CocoDetection returns (image, list of that image's annotations). Annotations stay as JSON dicts
val_dataset = datasets.CocoDetection(root, ann_file, transform=transforms.ToTensor())
image, anns = val_dataset[0]
print(len(val_dataset))                 # 5000
print(image.shape)                      # [3, height, width] (size differs per image)
print(anns[0]['bbox'], anns[0]['category_id'], anns[0]['iscrowd'])  # [x, y, width, height] and an ID in 1-90

# The number of objects differs per image, so batch them as lists
loader = DataLoader(val_dataset, batch_size=4, collate_fn=lambda batch: tuple(zip(*batch)))

# Mapping between category IDs (sparse in 1-90) and model output indices (0-79)
coco = val_dataset.coco
cat_ids = sorted(coco.getCatIds())
label_to_cat = {i: c for i, c in enumerate(cat_ids)}
print(len(cat_ids), cat_ids[:12])       # 80 [1, 2, ..., 11, 13] (12 is missing)


def to_coco_results(image_id, boxes_xyxy, scores, labels):
  """Convert model predictions into the format for evaluation (boxes as [x, y, width, height])"""
  results = []
  for (x1, y1, x2, y2), s, l in zip(boxes_xyxy.tolist(), scores.tolist(), labels.tolist()):
    results.append({'image_id': image_id, 'category_id': label_to_cat[l],
                    'bbox': [x1, y1, x2 - x1, y2 - y1], 'score': s})
  return results


# Evaluation loop (model is a trained detector; output boxes are [x1, y1, x2, y2], labels are 0-79)
# Some images have no annotations, so take image IDs from val_dataset.ids
# from pycocotools.cocoeval import COCOeval
# model.eval()
# results = []
# with torch.no_grad():
#   for idx in range(len(val_dataset)):
#     image, _ = val_dataset[idx]
#     out = model([image])[0]           # keep at most the 100 most confident detections per image
#     results += to_coco_results(val_dataset.ids[idx], out['boxes'], out['scores'], out['labels'])
# coco_dt = coco.loadRes(results)
# evaluator = COCOeval(coco, coco_dt, iouType='bbox')   # 'segm' for masks, 'keypoints' for keypoints
# evaluator.evaluate()
# evaluator.accumulate()
# evaluator.summarize()   # prints 12 values: AP, AP50, AP75, APS, APM, APL, AR1, AR10, AR100, ARS, ARM, ARL

FAQ

Q. Are COCO's "AP" and PASCAL VOC's "mAP" the same thing?
A.

The computation follows the same flow, but the definitions differ. VOC decides hits at IoU 0.5 only, while COCO averages over 10 thresholds from IoU 0.50 to 0.95. COCO's AP50 corresponds to the VOC criterion. Details are in the mAP article.

Q. Are there 80 categories or 91?
A.

The paper selected 91 categories, but boxes and masks exist for 80. Evaluation is also done on 80 categories. Because the IDs keep the numbering of the 91, they are scattered across 1–90.

Q. Should paper results be reported on the validation set or the test set?
A.

Results meant for comparison are usually reported on test-dev, which is scored by the evaluation server. Experiments that probe a method's components (ablations) are often run on the 5,000 validation images (val2017), so check which set each table uses.

References

  1. Lin, T.-Y., Maire, M., Belongie, S., Bourdev, L., Girshick, R., Hays, J., Perona, P., Ramanan, D., Zitnick, C. L., & Dollár, P. (2014). Microsoft COCO: Common Objects in Context. ECCV 2014.
  2. COCO Consortium. Detection Evaluation (official evaluation page).
  3. COCO Consortium. Keypoint Evaluation (keypoint evaluation page).
  4. COCO Consortium. Data Format, Download, Test Guidelines (data format, splits, and test rules).
  5. COCO Consortium. Terms of Use.
  6. Chen, X., Fang, H., Lin, T.-Y., Vedantam, R., Gupta, S., Dollár, P., & Zitnick, C. L. (2015). Microsoft COCO Captions: Data Collection and Evaluation Server.
  7. Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. NeurIPS 2015.
  8. He, K., Gkioxari, G., Dollár, P., & Girshick, R. (2017). Mask R-CNN. ICCV 2017.
  9. torchvision.datasets.CocoDetection (PyTorch documentation).