### Install pycococreator and pycocotools Source: https://context7.com/waspinator/pycococreator/llms.txt Install pycococreator directly from GitHub. Also includes commands to install pycocotools for Python 3 if needed. ```bash pip install git+git://github.com/waspinator/pycococreator.git@0.2.0 # Install pycocotools for Python 3 if needed: sudo apt-get install python3-dev pip install cython pip install git+git://github.com/waspinator/coco.git@2.1.0 ``` -------------------------------- ### Install pycococreator Source: https://github.com/waspinator/pycococreator/blob/master/README.md Install the pycococreator package from GitHub. Ensure you are using version 0.2.0. ```bash pip install git+git://github.com/waspinator/pycococreator.git@0.2.0 ``` -------------------------------- ### Install pycocotools for Python 3 Source: https://github.com/waspinator/pycococreator/blob/master/README.md Install pycocotools for Python 3. This requires installing python3-dev and cython first, then installing the coco package from GitHub. ```bash sudo apt-get install python3-dev pip install cython pip install git+git://github.com/waspinator/coco.git@2.1.0 ``` -------------------------------- ### Load and Display Image with Annotations Source: https://github.com/waspinator/pycococreator/blob/master/examples/shapes/visualize_coco.ipynb Loads an image, displays it, and then overlays its corresponding annotations for the selected category. ```python # load and display instance annotations image = io.imread(image_directory + image_data['file_name']) plt.imshow(image); plt.axis('off') pylab.rcParams['figure.figsize'] = (8.0, 10.0) annotation_ids = example_coco.getAnnIds(imgIds=image_data['id'], catIds=category_ids, iscrowd=None) annotations = example_coco.loadAnns(annotation_ids) example_coco.showAnns(annotations) ``` -------------------------------- ### Load COCO Annotation File Source: https://github.com/waspinator/pycococreator/blob/master/examples/shapes/visualize_coco.ipynb Initializes the COCO API with the specified annotation file. ```python example_coco = COCO(annotation_file) ``` -------------------------------- ### Full End-to-End COCO Dataset Creation Pipeline Source: https://context7.com/waspinator/pycococreator/llms.txt This script demonstrates the complete workflow for creating a COCO dataset JSON. It iterates over images, loads associated binary mask PNGs, creates image and annotation records, and writes the final COCO JSON file. Ensure you have the necessary directories and image files set up. ```python #!/usr/bin/env python3 import datetime import json import os import re import fnmatch import numpy as np from PIL import Image from pycococreatortools import pycococreatortools ROOT_DIR = 'train' IMAGE_DIR = os.path.join(ROOT_DIR, "shapes_train2018") ANNOTATION_DIR = os.path.join(ROOT_DIR, "annotations") INFO = { "description": "My Custom Dataset", "url": "https://example.com", "version": "1.0.0", "year": 2024, "contributor": "your_name", "date_created": datetime.datetime.utcnow().isoformat(' ') } LICENSES = [{"id": 1, "name": "MIT License", "url": "https://opensource.org/licenses/MIT"}] CATEGORIES = [ {'id': 1, 'name': 'square', 'supercategory': 'shape'}, {'id': 2, 'name': 'circle', 'supercategory': 'shape'}, {'id': 3, 'name': 'triangle', 'supercategory': 'shape'}, ] def filter_for_jpeg(root, files): pattern = r'|'.join([fnmatch.translate(t) for t in ['*.jpeg', '*.jpg']]) return [os.path.join(root, f) for f in files if re.match(pattern, f)] def filter_for_annotations(root, files, image_filename): png_pattern = r'|'.join([fnmatch.translate('*.png')]) prefix = os.path.splitext(os.path.basename(image_filename))[0] + '.*' candidates = [os.path.join(root, f) for f in files] candidates = [f for f in candidates if re.match(png_pattern, f)] return [f for f in candidates if re.match(prefix, os.path.splitext(os.path.basename(f))[0])] coco_output = {"info": INFO, "licenses": LICENSES, "categories": CATEGORIES, "images": [], "annotations": []} image_id = 1 segmentation_id = 1 for root, _, files in os.walk(IMAGE_DIR): for image_filename in filter_for_jpeg(root, files): image = Image.open(image_filename) # 1. Create image record image_info = pycococreatortools.create_image_info( image_id, os.path.basename(image_filename), image.size) coco_output["images"].append(image_info) # 2. Find and process each annotation mask for ann_root, _, ann_files in os.walk(ANNOTATION_DIR): for ann_filename in filter_for_annotations(ann_root, ann_files, image_filename): # Derive category from filename (e.g., "1001_circle_0.png" -> circle -> id 2) class_id = next( (x['id'] for x in CATEGORIES if x['name'] in ann_filename), None) if class_id is None: continue category_info = {'id': class_id, 'is_crowd': 'crowd' in image_filename} binary_mask = np.asarray( Image.open(ann_filename).convert('1')).astype(np.uint8) annotation_info = pycococreatortools.create_annotation_info( segmentation_id, image_id, category_info, binary_mask, image.size, tolerance=2) if annotation_info is not None: coco_output["annotations"].append(annotation_info) segmentation_id += 1 image_id += 1 output_path = os.path.join(ROOT_DIR, 'instances_train2024.json') with open(output_path, 'w') as f: json.dump(coco_output, f, indent=2) print(f"Wrote {len(coco_output['images'])} images and " f"{len(coco_output['annotations'])} annotations to {output_path}") # Wrote 2 images and 5 annotations to train/instances_train2024.json ``` -------------------------------- ### create_image_info Source: https://context7.com/waspinator/pycococreator/llms.txt Creates the image info dictionary required by the COCO format for a single image. It records the image dimensions, file name, capture date, license, and optional URLs. ```APIDOC ## create_image_info ### Description Creates the image info dictionary required by the COCO format for a single image. It records the image dimensions, file name, capture date, license, and optional URLs for COCO and Flickr. ### Method Signature ```python create_image_info(image_id, file_name, image_size, date_captured, license_id, coco_url, flickr_url) ``` ### Parameters - **image_id** (int) - Unique identifier for the image. - **file_name** (str) - The name of the image file. - **image_size** (tuple) - A tuple containing the width and height of the image (width, height). - **date_captured** (str) - The date and time the image was captured, in ISO format. - **license_id** (int) - The ID of the license applicable to the image. - **coco_url** (str) - Optional URL for the image on COCO. - **flickr_url** (str) - Optional URL for the image on Flickr. ### Request Example ```python import datetime from PIL import Image from pycococreatortools import pycococreatortools image = Image.open("train/shapes_train2018/1001.jpeg") image_info = pycococreatortools.create_image_info( image_id=1, file_name="1001.jpeg", image_size=image.size, # (width, height) date_captured=datetime.datetime.utcnow().isoformat(' '), license_id=1, coco_url="", flickr_url="" ) print(image_info) ``` ### Response Example ```json { "id": 1, "file_name": "1001.jpeg", "width": 512, "height": 512, "date_captured": "2024-01-15 10:30:00.000000", "license": 1, "coco_url": "", "flickr_url": "" } ``` ``` -------------------------------- ### Select Specific Category and Image Source: https://github.com/waspinator/pycococreator/blob/master/examples/shapes/visualize_coco.ipynb Retrieves image IDs for a specific category ('square') and loads a random image from that set. ```python category_ids = example_coco.getCatIds(catNms=['square']) image_ids = example_coco.getImgIds(catIds=category_ids) image_data = example_coco.loadImgs(image_ids[np.random.randint(0, len(image_ids))])[0] ``` -------------------------------- ### Define Dataset Paths Source: https://github.com/waspinator/pycococreator/blob/master/examples/shapes/visualize_coco.ipynb Specifies the directory for images and the path to the COCO annotation file. ```python image_directory = 'train/shapes_train2018/' annotation_file = 'train/annotations/instances_shape_train2018.json' ``` -------------------------------- ### create_annotation_info Source: https://context7.com/waspinator/pycococreator/llms.txt Converts a binary mask numpy array into a full COCO annotation dictionary. Automatically computes the bounding box and area; generates polygon segmentation for normal instances or RLE segmentation for crowd annotations. ```APIDOC ## create_annotation_info ### Description Converts a binary mask numpy array into a full COCO annotation dictionary. Automatically computes the bounding box and area via pycocotools; generates polygon segmentation for normal instances or RLE segmentation for crowd annotations. Returns `None` if the mask area is zero or no valid polygon can be extracted. ### Method Signature ```python create_annotation_info(annotation_id, image_id, category_info, binary_mask, image_size=None, tolerance=2, bounding_box=None) ``` ### Parameters - **annotation_id** (int) - Unique identifier for the annotation. - **image_id** (int) - The ID of the image this annotation belongs to. - **category_info** (dict) - A dictionary containing category information, including 'id' and 'is_crowd' (boolean). - **binary_mask** (numpy.ndarray) - A binary mask where white pixels represent the object. - **image_size** (tuple, optional) - A tuple (width, height) to resize the mask before encoding. Defaults to None. - **tolerance** (int, optional) - Polygon approximation tolerance in pixels. Defaults to 2. - **bounding_box** (list, optional) - A list representing the bounding box [x, y, width, height]. If None, it is auto-computed from the mask. ### Request Example (Normal Instance) ```python import numpy as np from PIL import Image from pycococreatortools import pycococreatortools # Load a binary mask (white pixels = object, black = background) binary_mask = np.asarray( Image.open("train/annotations/1001_circle_0.png").convert('1') ).astype(np.uint8) # Normal instance annotation (polygon segmentation) category_info = {'id': 2, 'is_crowd': False} annotation_info = pycococreatortools.create_annotation_info( annotation_id=1, image_id=1, category_info=category_info, binary_mask=binary_mask, image_size=(512, 512), # optional: resizes mask before encoding tolerance=2, # polygon approximation tolerance in pixels bounding_box=None # auto-computed from mask if None ) if annotation_info is not None: print(annotation_info) ``` ### Response Example (Normal Instance) ```json { "id": 1, "image_id": 1, "category_id": 2, "iscrowd": 0, "area": 4823.0, "bbox": [120.0, 95.0, 88.0, 87.0], "segmentation": [[165.0, 95.0, 208.0, 96.0, ...]], "width": 512, "height": 512 } ``` ### Request Example (Crowd Annotation) ```python # Crowd annotation (RLE segmentation) crowd_category_info = {'id': 2, 'is_crowd': True} crowd_annotation = pycococreatortools.create_annotation_info( annotation_id=2, image_id=1, category_info=crowd_category_info, binary_mask=binary_mask, image_size=(512, 512), tolerance=2 ) # crowd_annotation["iscrowd"] == 1 # crowd_annotation["segmentation"] == {"counts": [...], "size": [512, 512]} ``` ``` -------------------------------- ### Create COCO Image Info Record Source: https://context7.com/waspinator/pycococreator/llms.txt Generates the image info dictionary required by the COCO format for a single image. Requires image dimensions, file name, capture date, and license information. ```python import datetime from PIL import Image from pycococreatortools import pycococreatortools image = Image.open("train/shapes_train2018/1001.jpeg") image_info = pycococreatortools.create_image_info( image_id=1, file_name="1001.jpeg", image_size=image.size, # (width, height) date_captured=datetime.datetime.utcnow().isoformat(' '), license_id=1, coco_url="", flickr_url="" ) print(image_info) ``` -------------------------------- ### Display COCO Categories and Supercategories Source: https://github.com/waspinator/pycococreator/blob/master/examples/shapes/visualize_coco.ipynb Loads and prints the custom COCO categories and supercategories from the annotation file. ```python categories = example_coco.loadCats(example_coco.getCatIds()) category_names = [category['name'] for category in categories] print('Custom COCO categories: {} '.format(' '.join(category_names))) category_names = set([category['supercategory'] for category in categories]) print('Custom COCO supercategories: {}'.format(' '.join(category_names))) ``` -------------------------------- ### Import Libraries for COCO Visualization Source: https://github.com/waspinator/pycococreator/blob/master/examples/shapes/visualize_coco.ipynb Imports necessary libraries for working with COCO datasets, including image loading, plotting, and numpy operations. ```python %matplotlib inline from pycocotools.coco import COCO import numpy as np import skimage.io as io import matplotlib.pyplot as plt import pylab ``` -------------------------------- ### Create COCO Annotation Info from Binary Mask Source: https://context7.com/waspinator/pycococreator/llms.txt Converts a binary mask numpy array into a COCO annotation dictionary. Automatically computes bounding box and area. Generates polygon segmentation for normal instances or RLE for crowd annotations. Returns None if the mask area is zero or no valid polygon can be extracted. ```python import numpy as np from PIL import Image from pycococreatortools import pycococreatortools # Load a binary mask (white pixels = object, black = background) binary_mask = np.asarray( Image.open("train/annotations/1001_circle_0.png").convert('1') ).astype(np.uint8) # Normal instance annotation (polygon segmentation) category_info = {'id': 2, 'is_crowd': False} annotation_info = pycococreatortools.create_annotation_info( annotation_id=1, image_id=1, category_info=category_info, binary_mask=binary_mask, image_size=(512, 512), # optional: resizes mask before encoding tolerance=2, # polygon approximation tolerance in pixels bounding_box=None # auto-computed from mask if None ) if annotation_info is not None: print(annotation_info) # { # "id": 1, # "image_id": 1, # "category_id": 2, # "iscrowd": 0, # "area": 4823.0, # "bbox": [120.0, 95.0, 88.0, 87.0], # "segmentation": [[165.0, 95.0, 208.0, 96.0, ...]], # "width": 512, # "height": 512 # } # Crowd annotation (RLE segmentation) crowd_category_info = {'id': 2, 'is_crowd': True} crowd_annotation = pycococreatortools.create_annotation_info( annotation_id=2, image_id=1, category_info=crowd_category_info, binary_mask=binary_mask, image_size=(512, 512), tolerance=2 ) # crowd_annotation["iscrowd"] == 1 # crowd_annotation["segmentation"] == {"counts": [...], "size": [512, 512]} ``` -------------------------------- ### binary_mask_to_polygon Source: https://context7.com/waspinator/pycococreator/llms.txt Converts a binary mask to a list of polygons. Each polygon is a flat list of coordinates [x1, y1, x2, y2, ...]. ```APIDOC ## `binary_mask_to_polygon` — Convert a binary mask to polygon format Converts a binary mask to COCO's polygon format. The mask is traversed in row-major order, and the result is a list of polygons. Each polygon is a flat list of coordinates [x1, y1, x2, y2, ...] with at least 3 points. ```python import numpy as np from pycococreatortools import pycococreatortools # Create a simple circular mask mask = np.zeros((100, 100), dtype=np.uint8) from PIL import Image, ImageDraw img = Image.fromarray(mask) draw = ImageDraw.Draw(img) draw.ellipse([30, 30, 70, 70], fill=1) binary_mask = np.asarray(img) polygons = pycococreatortools.binary_mask_to_polygon(binary_mask, tolerance=1) print(len(polygons)) # 1 (one connected region) print(polygons[0][:8]) # [50.0, 30.0, 55.0, 31.0, 60.0, 33.0, 64.0, 36.0, ...] # Each polygon is a flat list: [x1, y1, x2, y2, ...] with at least 3 points ``` ``` -------------------------------- ### binary_mask_to_rle Source: https://context7.com/waspinator/pycococreator/llms.txt Converts a binary mask to COCO's uncompressed Run-Length Encoding (RLE) format. The output is compatible with pycocotools.mask.decode() for reconstruction. ```APIDOC ## `binary_mask_to_rle` — Convert a binary mask to uncompressed RLE Converts a binary mask to COCO's uncompressed (non-LZMA) Run-Length Encoding format. The mask is traversed in column-major (Fortran) order, and the result contains alternating counts of off/on pixel runs. Used internally by `create_annotation_info` when `is_crowd=True`. ```python import numpy as np from pycococreatortools import pycococreatortools binary_mask = np.array([ [0, 0, 1, 1], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 1, 1], ], dtype=np.uint8) rle = pycococreatortools.binary_mask_to_rle(binary_mask) print(rle) # {'counts': [4, 3, 1, 2, 1, 2, 3, 0], 'size': [4, 4]} # Compatible with pycocotools.mask.decode() for reconstruction ``` ``` -------------------------------- ### resize_binary_mask Source: https://context7.com/waspinator/pycococreator/llms.txt Resizes a 2D binary mask to a target image size using PIL nearest-neighbor resampling. Returns a boolean numpy array. ```APIDOC ## `resize_binary_mask` — Resize a binary mask to a target image size Resizes a 2D binary mask to a new `(width, height)` size using PIL nearest-neighbour resampling, then returns a boolean numpy array. Used inside `create_annotation_info` when `image_size` differs from the mask's native dimensions. ```python import numpy as np from pycococreatortools import pycococreatortools # Small 50x50 mask mask = np.zeros((50, 50), dtype=np.bool_) mask[10:40, 10:40] = True # Resize to match a 512x512 image resized = pycococreatortools.resize_binary_mask(mask, new_size=(512, 512)) print(resized.shape) # (512, 512) print(resized.dtype) # bool print(resized.sum()) # ~92160 (proportionally larger filled region) ``` ``` -------------------------------- ### Convert Binary Mask to Polygon Source: https://context7.com/waspinator/pycococreator/llms.txt Converts a binary mask to a list of polygons. The mask is first converted to a PIL Image, then drawn upon, and finally converted back to a numpy array. Ensure the mask is a numpy array with uint8 dtype. ```python import numpy as np from PIL import Image, ImageDraw import pycococreatortools mask = np.zeros((100, 100), dtype=np.uint8) img = Image.fromarray(mask) draw = ImageDraw.Draw(img) draw.ellipse([30, 30, 70, 70], fill=1) binary_mask = np.asarray(img) polygons = pycococreatortools.binary_mask_to_polygon(binary_mask, tolerance=1) print(len(polygons)) print(polygons[0][:8]) ``` -------------------------------- ### Convert Binary Mask to RLE Source: https://context7.com/waspinator/pycococreator/llms.txt Converts a binary mask to COCO's uncompressed Run-Length Encoding format. The mask is traversed in column-major order. This is used internally by `create_annotation_info` when `is_crowd=True`. The output is compatible with pycocotools.mask.decode() for reconstruction. ```python import numpy as np from pycococreatortools import pycococreatortools binary_mask = np.array([ [0, 0, 1, 1], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 1, 1], ], dtype=np.uint8) rle = pycococreatortools.binary_mask_to_rle(binary_mask) print(rle) ``` -------------------------------- ### Resize Binary Mask Source: https://context7.com/waspinator/pycococreator/llms.txt Resizes a 2D binary mask to a new (width, height) size using PIL nearest-neighbour resampling. Returns a boolean numpy array. This is used inside `create_annotation_info` when the image size differs from the mask's native dimensions. ```python import numpy as np from pycococreatortools import pycococreatortools mask = np.zeros((50, 50), dtype=np.bool_) mask[10:40, 10:40] = True resized = pycococreatortools.resize_binary_mask(mask, new_size=(512, 512)) print(resized.shape) print(resized.dtype) print(resized.sum()) ``` -------------------------------- ### Convert Binary Mask to COCO Polygon Segmentation Source: https://context7.com/waspinator/pycococreator/llms.txt Extracts contours from a binary mask and returns a list of flattened polygon coordinate sequences. Pads the mask by 1 pixel and applies Ramer-Douglas-Peucker simplification. ```python import numpy as np from pycococreatortools import pycococreatortools ``` -------------------------------- ### binary_mask_to_polygon Source: https://context7.com/waspinator/pycococreator/llms.txt Extracts contours from a binary mask and returns a list of flattened polygon coordinate sequences in COCO format. Applies simplification controlled by `tolerance`. ```APIDOC ## binary_mask_to_polygon ### Description Extracts contours from a binary mask and returns a list of flattened `[x, y, x, y, ...]` polygon coordinate sequences in COCO format. Pads the mask by 1 pixel on all sides to correctly handle objects touching image edges. Applies Ramer-Douglas-Peucker simplification controlled by `tolerance`. ### Method Signature ```python binary_mask_to_polygon(binary_mask, tolerance=2) ``` ### Parameters - **binary_mask** (numpy.ndarray) - The input binary mask. - **tolerance** (int, optional) - The tolerance for the Ramer-Douglas-Peucker simplification. Defaults to 2. ### Request Example ```python import numpy as np from pycococreatortools import pycococreatortools # Assuming binary_mask is a numpy array loaded from an image # polygons = pycococreatortools.binary_mask_to_polygon(binary_mask, tolerance=3) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.