bnsreenu / digitalsreeni-image-annotator

A python based GUI to annotate images and save annotations as COCO style JSON format.
Other
112 stars 17 forks source link

Exporting labeled images/ semantic images #14

Closed Rodrigo-Zugasti closed 42 minutes ago

Rodrigo-Zugasti commented 5 hours ago

Hello, I have a project where I labeled .bmp images (5mpx) , just 1 class using the polygon feature. For some reason, when I export the labeled images they are all black. I was hoping to get a binary mask.

Rodrigo-Zugasti commented 2 hours ago

Solution for COCO dataset

import os import cv2 import numpy as np import json from pycocotools.coco import COCO from pycocotools import mask as maskUtils

Paths to your dataset

dir='your dir\' images_path = dir+ 'images\' annotations_path = dir+'mask.json' output_path = dir+ '\masks'

Create output directory if it doesn't exist

os.makedirs(output_path, exist_ok=True)

Load COCO annotations

coco = COCO(annotations_path)

Get all image ids

image_ids = coco.getImgIds()

Function to create a binary mask from COCO annotations

def create_mask(image_shape, annotations): mask = np.zeros(image_shape[:2], dtype=np.uint8) for ann in annotations: rle = coco.annToRLE(ann) m = maskUtils.decode(rle) mask = np.maximum(mask, m) return mask * 255

Process each image

for image_id in image_ids: image_info = coco.loadImgs(image_id)[0] image_path = os.path.join(images_path, image_info['file_name'])

# Read image
image = cv2.imread(image_path)
if image is None:
    continue

# Get annotations for the image
annotation_ids = coco.getAnnIds(imgIds=image_id)
annotations = coco.loadAnns(annotation_ids)

# Create mask
mask = create_mask(image.shape, annotations)

# Save mask
mask_path = os.path.join(output_path, os.path.splitext(image_info['file_name'])[0] + '_mask.png')
cv2.imwrite(mask_path, mask)

print("Masks generated successfully!")

bnsreenu commented 42 minutes ago

Just tested the functionality and it is working fine, no issues. By definition, labeled images store objects with pixels values 1, 2, 3, etc. These labeled images when opened in default Windows or mac or Linux image viewer is not going to show these objects as they adjust the range to 0 - 255. Please open the labeled images using python or scientific image programs like imageJ.

bnsreenu commented 42 minutes ago

Closing the issue as there is no bug and the application is working fine.