I'll help you complete the RLE (Run-Length Encoding) logic for converting segmentation masks to Label Studio format. Here's the updated script with the RLE conversion implemented:
import numpy as np
from datasets import load_from_disk
import io
import base64
import os
import json
from PIL import Image
# load the dataset
dataset_path = "hf_furnace_tubes"
dataset = load_from_disk(dataset_path)
# function to convert an image to base64
def image_to_base64(img):
buffered = io.BytesIO()
img.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8")
# function to convert a binary mask to RLE format
def mask_to_rle(mask):
"""
Convert a binary mask to RLE format.
Args:
mask: numpy array of shape (height, width) with binary values
Returns:
list: RLE encoded mask as a list of integers
"""
# Flatten the mask in column-major order (Fortran style) as Label Studio expects
flat_mask = mask.flatten(order='F')
# Find where the mask changes value
changes = np.diff(np.concatenate(([0], flat_mask, [0])))
# Get the positions where changes occur
change_positions = np.where(changes != 0)[0]
# Create RLE encoding
rle = []
for i in range(0, len(change_positions), 2):
if i + 1 < len(change_positions):
start = change_positions[i]
length = change_positions[i + 1] - change_positions[i]
rle.extend([start, length])
return rle
# function to extract mask for a specific segment
def extract_segment_mask(label_image, segment_id):
"""
Extract binary mask for a specific segment ID.
Args:
label_image: PIL Image or numpy array with segment IDs
segment_id: ID of the segment to extract
Returns:
numpy array: Binary mask where segment pixels are 1, others are 0
"""
# Convert PIL Image to numpy array if needed
if isinstance(label_image, Image.Image):
label_array = np.array(label_image)
else:
label_array = label_image
# Create binary mask for the specific segment
mask = (label_array == segment_id).astype(np.uint8)
return mask
# create output directory
output_dir = "label_studio_import_v2"
os.makedirs(output_dir, exist_ok=True)
# process each split
for split in dataset.keys():
split_data = dataset[split]
label_studio_tasks = []
for i, example in enumerate(split_data):
# get the image and label
image = example["image"]
label_image = example["label"]
segments_info = example.get("segments_info", [])
# label studio task
task = {
"id": i,
"data": {
"image": image_to_base64(image)
},
"annotations": [{
"id": i,
"result": []
}]
}
# add brush labels based on the segmentation mask
for segment in segments_info:
segment_id = segment["id"]
category_id = segment["category_id"]
# find the label name for this category_id
label_name = None
for class_name, class_id in example.get("semantic_class_to_id", {}).items():
if class_id == category_id:
label_name = class_name
break
if label_name:
# extract mask for this segment
segment_mask = extract_segment_mask(label_image, segment_id)
# convert segmentation mask to RLE format
rle_mask = mask_to_rle(segment_mask)
# only add if the mask is not empty
if len(rle_mask) > 0:
task["annotations"][0]["result"].append({
"original_width": image.width,
"original_height": image.height,
"image_rotation": 0,
"value": {
"format": "rle",
"rle": rle_mask,
"brushlabels": [label_name]
},
"id": f"segment_{i}_{segment_id}",
"from_name": "tag",
"to_name": "image",
"type": "brushlabels",
"origin": "manual"
})
label_studio_tasks.append(task)
# write the tasks to a JSON file
with open(os.path.join(output_dir, f"{split}_tasks.json"), "w") as f:
json.dump(label_studio_tasks, f, indent=2)
print(f"Conversion complete. Files saved to {output_dir}")