for split in dataset.keys():
split_data = dataset[split]
label_studio_tasks = []
code
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:
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:
# convert segmentation mask to RLE format
# this is a simplified example - you'll need to implement proper RLE conversion
task["annotations"][0]["result"].append({
"original_width": image.width,
"original_height": image.height,
"image_rotation": 0,
"value": {
"format": "rle",
"rle": [], # convert mask to RLE format
"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)
print(f"Conversion complete. Files saved to {output_dir}")
Assistant
To complete the RLE (Run-Length Encoding) logic in your script, you need to convert the segmentation mask into RLE format. Below is the updated script with the RLE conversion logic added. The RLE conversion is typically done by encoding the segmentation mask into a compact format where consecutive pixels with the same value are represented as a count.
import os
import io
import base64
import json
from PIL import Image
from datasets import load_from_disk
import numpy as np
# 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 segmentation mask to RLE format
def mask_to_rle(mask, width, height):
mask = mask.reshape(-1)
rle = []
prev_val = 0
count = 0
for val in mask:
if val == prev_val:
count += 1
else:
rle.append(count)
prev_val = val
count = 1
rle.append(count)
return rle
# 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:
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 the segmentation mask for the current segment
mask = (label_image == category_id).astype(np.uint8)
# Convert segmentation mask to RLE format
rle = mask_to_rle(mask, width=image.width, height=image.height)
task["annotations"][0]["result"].append({
"original_width": image.width,
"original_height": image.height,
"image_rotation": 0,
"value": {
"format": "rle",
"rle": rle,
"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=4)
print(f"Conversion complete. Files saved to {output_dir}")
Key Changes:
RLE Conversion Function (mask_to_rle):
This function takes a segmentation mask and converts it into RLE format.
It flattens the mask and encodes consecutive pixels with the same value as a count.
Mask Extraction:
For each segment, the corresponding mask is extracted by checking where the label_image matches the category_id.
RLE Integration:
The RLE-encoded mask is added to the Label Studio task under the "rle" key in the "value" dictionary.
This script should now correctly convert segmentation masks to RLE format and prepare the data for import into Label Studio.