cvtk.data

This module provides classes and functions for working with image records, annotations, and datasets. It supports multiple annotation formats including bounding boxes, segmentation masks, and COCO format.

Main Classes

  • Bbox: Bounding box representation with multiple coordinate formats (xyxy, xywh, cxcywh, etc.)

  • Segm: Segmentation representation supporting masks, RLE, and polygon formats

  • InstanceAnnotation: Combined annotation with label, bounding box, segmentation, and score

  • ImageRecord: Single image with its annotations

  • ImageDataset: Collection of image records with dataset-level operations

API Reference

cvtk.data.coco.crop(input: str | dict, image_root: str | None = None, output: str | None = None) None[source]

Crop objects from images based on COCO annotations.

Extracts individual annotated objects from images and saves them as separate cropped images. Each crop is named using the image filename, category ID, and bounding box coordinates.

Parameters:
  • input (str|dict) – COCO annotation data. Can be a file path to JSON or a dict object.

  • image_root (str|None) – Base directory for image paths. If None, uses paths as stored in annotations. Default is None.

  • output (str|None) – Directory to save cropped object images. Directory created if needed.

Returns:

None. Cropped images saved to output directory.

Raises:

ValueError – If output directory not specified or image not found for annotation.

Examples

>>> crop('annotations.json', output='cropped_objects/')
>>> crop('annotations.json', image_root='/data/images', output='crops/')
cvtk.data.coco.combine(input: str | dict | list[str] | list[dict] | tuple[str] | tuple[dict], image_root: str | None = None, output: str | None = None, ensure_ascii: bool = False, indent: int | None = 4) dict[source]

Merge multiple COCO annotation files into one.

Combines multiple COCO datasets by merging all images, annotations, and categories. All IDs are re-indexed sequentially to avoid conflicts. Duplicate categories are deduplicated by name.

Parameters:
  • input (str|dict|list|tuple) – Single or multiple COCO sources. Can be file path(s) or dict object(s).

  • image_root (str|None) – Base directory for image paths. If None, uses paths from annotations. Default is None.

  • output (str|None) – File path to save merged COCO annotation. If None, only returns data without saving. Default is None.

  • ensure_ascii (bool) – If True, escapes non-ASCII characters in JSON output. Default is False.

  • indent (int|None) – JSON indentation level. If None, compact output. Default is 4.

Returns:

Merged COCO annotation data with re-indexed IDs and deduplicated categories.

Return type:

dict

Examples

>>> combined = combine(['ann1.json', 'ann2.json'], output='merged.json')
>>> combined = combine([coco_dict1, coco_dict2], image_root='/data/images')
cvtk.data.coco.split(input: str | dict, image_root: str | None = None, ratios: list[float] | tuple[float] = [0.8, 0.1, 0.1], shuffle: bool = True, random_seed: int | None = None, output: str | None = None, ensure_ascii=False, indent=4) list[dict][source]

Split COCO annotation data into train/validation/test subsets.

Partitions images into multiple subsets with specified ratios. Annotations follow images. Categories are shared across all subsets. Optionally shuffles before splitting for randomization.

Parameters:
  • input (str|dict) – COCO annotation data as file path or dict object.

  • image_root (str|None) – Base directory for image paths. If None, uses paths from annotations. Default is None.

  • ratios (list|tuple) – Subset size ratios. Sum must equal 1.0. Default is [0.8, 0.1, 0.1].

  • shuffle (bool) – If True, randomize image order before splitting. Default is True.

  • random_seed (int|None) – Seed for shuffling reproducibility. If None, uses random state. Default is None.

  • output (str|None) – Base path for saving subsets. Each file appended with .0, .1, .2, etc. Default is None.

  • ensure_ascii (bool) – If True, escapes non-ASCII characters in JSON output. Default is False.

  • indent (int|None) – JSON indentation level. If None, compact output. Default is 4.

Returns:

List of COCO dicts, one per subset, in order matching ratios.

Return type:

list[dict]

Raises:

ValueError – If ratios don’t sum to approximately 1.0.

Examples

>>> train, valid, test = split('data.json', ratios=[0.7, 0.2, 0.1], output='split')
>>> subsets = split(coco_dict, shuffle=True, random_seed=42)
cvtk.data.coco.reindex(input: str | dict, image_root: str | None = None, image_id=True, category_id=True, output: str | None = None, ensure_ascii=False, indent=4) dict[source]

Re-index image and category IDs sequentially.

Renumbers image and/or category IDs to be sequential (1, 2, 3, …) and updates all annotation references accordingly. Useful after removing items or merging datasets.

Parameters:
  • input (str|dict) – COCO annotation data as file path or dict object.

  • image_root (str|None) – Base directory for image paths. If None, uses paths from annotations. Default is None.

  • image_id (bool) – If True, re-index image IDs sequentially. Default is True.

  • category_id (bool) – If True, re-index category IDs sequentially. Default is True.

  • output (str|None) – File path to save re-indexed data. If None, only returns without saving. Default is None.

  • ensure_ascii (bool) – If True, escapes non-ASCII characters in JSON output. Default is False.

  • indent (int|None) – JSON indentation level. If None, compact output. Default is 4.

Returns:

Re-indexed COCO annotation data with updated ID references.

Return type:

dict

Examples

>>> reindexed = reindex('sparse_ids.json', output='dense_ids.json')
>>> reindexed = reindex(coco_dict, image_id=True, category_id=False)
cvtk.data.coco.remove(input: str | dict, image_root: str | None = None, images: list | None = None, categories: list | None = None, annotations: list | None = None, output: str | None = None, ensure_ascii=False, indent=4) dict[source]

Remove specific images, categories, or annotations from COCO data.

Deletes specified items and all related annotations. Related annotations are also removed when their parent image or category is deleted. Original IDs are preserved (not re-indexed).

Parameters:
  • input (str|dict) – COCO annotation data as file path or dict object.

  • image_root (str|None) – Base directory for image paths. If None, uses paths from annotations. Default is None.

  • images (list|None) – Images to remove. Items can be image IDs (int) or filenames (str). Default is None.

  • categories (list|None) – Categories to remove. Items can be category IDs (int) or names (str). Default is None.

  • annotations (list|None) – Annotations to remove by annotation ID (int). Default is None.

  • output (str|None) – File path to save filtered data. If None, only returns without saving. Default is None.

  • ensure_ascii (bool) – If True, escapes non-ASCII characters in JSON output. Default is False.

  • indent (int|None) – JSON indentation level. If None, compact output. Default is 4.

Returns:

COCO data with specified items removed.

Return type:

dict

Examples

>>> remove('data.json', images=[1, 5, 10], output='filtered.json')
>>> remove(coco_dict, categories=['background'], annotations=[1, 2, 3])
cvtk.data.coco.stats(input: str | dict, image_root: str | None = None, output: str | None = None, ensure_ascii: bool = False, indent: int | None = 4) dict[source]

Calculate dataset statistics from COCO annotations.

Computes summary statistics including total images, categories, and annotation counts per category.

Parameters:
  • input (str|dict) – COCO annotation data as file path or dict object.

  • image_root (str|None) – Base directory for image paths. If None, uses paths from annotations. Default is None.

  • output (str|None) – File path to save statistics. If None, only returns without saving. Default is None.

  • ensure_ascii (bool) – If True, escapes non-ASCII characters in JSON output. Default is False.

  • indent (int|None) – JSON indentation level. If None, compact output. Default is 4.

Returns:

Statistics containing ‘n_images’, ‘n_categories’, and ‘n_annotations’ (per category).

Return type:

dict

Examples

>>> stats_data = stats('data.json')
>>> print(f"Total images: {stats_data['n_images']}")
>>> print(f"Annotations per class: {stats_data['n_annotations']}")
cvtk.data.coco.calc_stats(gt: str | dict, pred: str | dict, image_root: str | None = None, image_by: Literal['id', 'file_name'] = 'id', category_by: Literal['id', 'name'] = 'id', iouType: Literal['bbox', 'segm'] = 'bbox', metrics_labels=None) dict[source]

Calculate object detection and segmentation metrics using COCO evaluation.

Computes standard COCO metrics (AP, AR) for object detection and instance segmentation tasks. Supports flexible ID mapping between ground truth and predictions via image filenames or category names. Uses pycocotools COCOeval for metric computation.

Parameters:
  • gt (str|dict) – Ground truth COCO annotations as file path or dict object.

  • pred (str|dict) – Predicted COCO annotations as file path or dict object.

  • image_root (str|None) – Base directory for image paths. If None, uses paths from annotations. Default is None.

  • image_by (Literal['id', 'file_name']) – Attribute for mapping images between gt and pred: - ‘id’: Match by image ID (must be identical) - ‘file_name’: Match by filename (allows different IDs). Default is ‘id’.

  • category_by (Literal['id', 'name']) – Attribute for mapping categories: - ‘id’: Match by category ID (must be identical) - ‘name’: Match by category name (allows different IDs). Default is ‘id’.

  • iouType (Literal['bbox', 'segm']) – Evaluation type: ‘bbox’ for object detection, ‘segm’ for segmentation. Default is ‘bbox’.

  • metrics_labels (list|tuple|None) – Specific metric labels to compute (e.g., [‘AP@[0.50:0.95|all|100]’]). If None, computes all 12 standard COCO metrics. Default is None.

Returns:

Metrics with structure {‘stats’: {…}, ‘class_stats’: {…}}:
  • ’stats’: Overall metrics for each requested label

  • ’class_stats’: Per-category metrics with class names as keys

Return type:

dict

Raises:
  • ValueError – If iouType not in [‘bbox’, ‘segm’], metrics_labels empty, or metric parsing fails.

  • TypeError – If metrics_labels not list or tuple.

Examples

>>> results = calc_stats('gt.json', 'pred.json', iouType='bbox')
>>> print(f"AP: {results['stats']['AP@[0.50:0.95|all|100]']}")
>>> results = calc_stats(gt_dict, pred_dict, category_by='name', image_by='file_name')