I have a hugging face dataset with annotated images. I would like to add labels to these images using label-studio.
I need to convert the current dataset to a compatible type.
Label studio needs JSONs of the form: {"data": {"column1"..}, "predictions": [{..."column2"}]
Example: Export JSON from label studio:
[{"id":1,"annotations":[{"id":4,"completed_by":1,"result":[{"original_width":325,"original_height":243,"image_rotation":0,"value":{"format":"rle","rle":[0,4,209,252,57,27,...],"brushlabels":["TUBE"]},"id":"z23YLwWuiO","from_name":"tag","to_name":"image","type":"brushlabels","origin":"manual"},...
The huggingface file structure breaks down as follows:
The dataset_dict.json is of the form: {"splits": ["train", "val", "test"]}
The data_info.json is of the form:
{
"citation": "",
"description": "",
"features": {
"image": {
"_type": "Image"
},
"label": {
"_type": "Image"
},
"segments_info": [
{
"category_id": {
"dtype": "int64",
"_type": "Value"
},
"id": {
"dtype": "int32",
"_type": "Value"
}
}
],
"semantic_class_to_id": {
"TUBE": {
"dtype": "int64",
"_type": "Value"
}
}
},
"homepage": "",
"license": ""
}
The state.json is of the form:
{
"_data_files": [
{
"filename": "data-00000-of-00001.arrow"
}
],
"_fingerprint": "95c2b8e99c197d5f",
"_format_columns": null,
"_format_kwargs": {},
"_format_type": null,
"_output_all_columns": false,
"_split": null
}
How can I convert my huggingface dataset to be compatible with label studio for prelabeled images?
Assistant
This is an excellent use case for pre-labeling in Label Studio! The core idea is to convert your existing Hugging Face dataset's image and mask annotations into Label Studio's JSON format, specifically the predictions block.
Here's a step-by-step guide and Python script to achieve this.
Understanding the Conversion Logic
Hugging Face image -> Label Studio data.image:
Your Hugging Face dataset image feature is a PIL Image object.
Label Studio needs an image URL. For local files, this is typically a file:// URL. You'll save each image from the HF dataset to a local directory and then use its path.
Hugging Face label (mask) + segments_info -> Label Studio predictions.result.brushlabels:
Your label feature is a semantic segmentation mask (PIL Image). Its pixel values likely correspond to category_ids.
segments_info gives you details about the segments and their category_ids.
semantic_class_to_id maps class names (e.g., "TUBE") to category_ids.
Label Studio's brushlabels require a Run-Length Encoding (RLE) of the mask. You'll need to extract individual binary masks for each category_id present in the label image, convert them to RLE, and associate them with their respective class names.
Label Studio Project Setup (XML Configuration):
You'll need a Label Studio project with an XML configuration that includes an <Image> tag and a <BrushLabels> tag. The name attributes of these tags are crucial because they directly correspond to the from_name and to_name fields in your generated JSON.
Prerequisites
Install Libraries:
bash
pip install datasets Pillow numpy pycocotools
datasets: To load your Hugging Face dataset.
Pillow: For image manipulation (already a dependency of datasets).
numpy: For array operations on image masks.
pycocotools: Contains functions for converting binary masks to RLE and vice versa, which Label Studio uses for brushlabels.
Label Studio Installation:
bash
pip install label-studio
Step 1: Label Studio Project XML Configuration
Create a file named config.xml (or similar) for your Label Studio project:
xml
<View>
<Image name="image" value="$image" />
<BrushLabels name="tag" toName="image">
<Label value="TUBE" background="rgba(255, 0, 0, 0.7)" />
<!-- Add other labels if your dataset has more categories, e.g., <Label value="OTHER_CLASS" /> -->
</BrushLabels>
</View>
Important:
Image name="image": This name attribute ("image") will be used as to_name in the JSON result and as the key in data.
BrushLabels name="tag": This name attribute ("tag") will be used as from_name in the JSON result.
<Label value="TUBE" ...>: Make sure the value attributes here match the class names from your semantic_class_to_id (e.g., "TUBE").
Step 2: Python Script for Conversion
python
import os
import json
from datasets import load_from_disk
import numpy as np
from PIL import Image
from pycocotools import mask as mask_utils # For RLE conversion
# --- Configuration ---
HF_DATASET_PATH = "./dataset" # Path to your Hugging Face dataset directory
OUTPUT_DIR = "./label_studio_import" # Directory to save images and JSON
SPLIT_NAME = "train" # Which split to convert (e.g., "train", "val", "test")
# Label Studio's 'from_name' and 'to_name' from your XML config
# Make sure these match the 'name' attributes in your config.xml!
LS_BRUSHLABELS_FROM_NAME = "tag"
LS_IMAGE_TO_NAME = "image"
# --- End Configuration ---
def convert_mask_to_rle(mask_array):
"""
Converts a binary mask (NumPy array) to COCO RLE format.
mask_array: 2D numpy array, 1 for foreground, 0 for background.
"""
# Ensure mask is Fortran contiguous for pycocotools
mask = np.asfortranarray(mask_array.astype(np.uint8))
rle = mask_utils.encode(mask)
rle['counts'] = rle['counts'].decode('utf-8') # Decode bytes to string
return rle
def main():
print(f"Loading Hugging Face dataset from: {HF_DATASET_PATH}")
dataset = load_from_disk(HF_DATASET_PATH)
if SPLIT_NAME not in dataset:
print(f"Error: Split '{SPLIT_NAME}' not found in the dataset.")
print(f"Available splits: {list(dataset.keys())}")
return
split_dataset = dataset[SPLIT_NAME]
print(f"Converting split: {SPLIT_NAME} with {len(split_dataset)} examples.")
output_images_dir = os.path.join(OUTPUT_DIR, "images")
os.makedirs(output_images_dir, exist_ok=True)
print(f"Images will be saved to: {output_images_dir}")
label_studio_tasks = []
# Get semantic_class_to_id mapping for convenience
# Accessing features.semantic_class_to_id from the first example
# This assumes it's consistent across the dataset.
semantic_class_to_id = split_dataset.features['semantic_class_to_id']
id_to_semantic_class = {v: k for k, v in semantic_class_to_id.items()}
print(f"Semantic class mapping: {id_to_semantic_class}")
for i, example in enumerate(split_dataset):
image_id = f"{SPLIT_NAME}_{i}"
image_pil = example['image']
mask_pil = example['label'] # This is the semantic segmentation mask
# Save the original image
image_filename = f"{image_id}.png"
image_path = os.path.join(output_images_dir, image_filename)
image_pil.save(image_path)
# Convert PIL mask to numpy array for processing
mask_np = np.array(mask_pil) # Should be (H, W) where values are category_ids
original_width, original_height = image_pil.size
predictions_results = []
# Find unique category IDs present in this specific mask
# This handles cases where some categories might not be in every image
unique_category_ids = np.unique(mask_np)
for cat_id in unique_category_ids:
if cat_id == 0: # Assuming 0 is background/no-label
continue
class_name = id_to_semantic_class.get(cat_id)
if class_name is None:
print(f"Warning: Category ID {cat_id} found in mask but not in semantic_class_to_id. Skipping.")
continue
# Create a binary mask for the current category_id
# Where pixels matching cat_id are 1, others are 0
binary_mask = (mask_np == cat_id).astype(np.uint8)
# Convert binary mask to RLE
rle_mask = convert_mask_to_rle(binary_mask)
# Construct the Label Studio result object for this segment
result = {
"original_width": original_width,
"original_height": original_height,
"image_rotation": 0,
"value": {
"format": "rle",
"rle": rle_mask,
"brushlabels": [class_name] # List of labels for this segment
},
"id": f"{image_id}_{class_name}", # Unique ID for this specific annotation
"from_name": LS_BRUSHLABELS_FROM_NAME,
"to_name": LS_IMAGE_TO_NAME,
"type": "brushlabels",
"origin": "prefill" # Indicates this was automatically generated
}
predictions_results.append(result)
# Construct the full Label Studio task for this image
task = {
"data": {
# Use file:/// for local paths.
# Label Studio needs to be configured to allow file access or serve from a source directory.
"image": f"file://{os.path.abspath(image_path)}"
},
"predictions": [
{
"model_version": "huggingface_dataset_import",
"score": 1.0, # Placeholder score if not applicable
"result": predictions_results
}
]
}
label_studio_tasks.append(task)
output_json_path = os.path.join(OUTPUT_DIR, f"{SPLIT_NAME}_label_studio_tasks.json")
with open(output_json_path, 'w') as f:
json.dump(label_studio_tasks, f, indent=2)
print(f"\nConversion complete! JSON file saved to: {output_json_path}")
print(f"Remember to set up your Label Studio project with the correct config.xml and import this JSON file.")
print("If using 'file://' URLs, ensure Label Studio is started with '--allow-file-access' or the images are in a directory served by LS.")
if __name__ == "__main__":
# Create a dummy HuggingFace dataset for demonstration if not already present
if not os.path.exists(HF_DATASET_PATH):
print("Creating a dummy Hugging Face dataset for demonstration...")
from datasets import Dataset, Features, Value, Image as HFImage
import PIL.ImageDraw
import io
# Create a dummy image
img_size = (100, 100)
img_pil = Image.new('RGB', img_size, color = 'white')
d = PIL.ImageDraw.Draw(img_pil)
d.ellipse((10, 10, 50, 50), fill=(255, 0, 0)) # Red circle
d.rectangle((60, 60, 90, 90), fill=(0, 255, 0)) # Green square
# Create a dummy mask image (semantic segmentation)
# 0: background, 1: TUBE, 2: OTHER_THING
mask_pil = Image.new('L', img_size, color=0) # 'L' for grayscale (1 byte per pixel)
d_mask = PIL.ImageDraw.Draw(mask_pil)
d_mask.ellipse((10, 10, 50, 50), fill=1) # TUBE (category_id 1)
d_mask.rectangle((60, 60, 90, 90), fill=2) # OTHER_THING (category_id 2)
# Convert PIL images to bytes for HF dataset
def pil_to_bytes(pil_img):
buffer = io.BytesIO()
pil_img.save(buffer, format="PNG")
return {"bytes": buffer.getvalue()}
# Create a dataset with 2 dummy examples
data = [
{
"image": pil_to_bytes(img_pil),
"label": pil_to_bytes(mask_pil),
"segments_info": [
{"category_id": 1, "id": 101},
{"category_id": 2, "id": 102}
],
"semantic_class_to_id": {"TUBE": 1, "OTHER_THING": 2}
},
{
"image": pil_to_bytes(Image.new('RGB', (80, 80), color='blue')),
"label": pil_to_bytes(Image.new('L', (80, 80), color=1)), # Only TUBE
"segments_info": [
{"category_id": 1, "id": 201}
],
"semantic_class_to_id": {"TUBE": 1, "OTHER_THING": 2}
}
]
# Define features for the dummy dataset
features = Features({
"image": HFImage(),
"label": HFImage(),
"segments_info": [
{
"category_id": Value(dtype="int64"),
"id": Value(dtype="int32")
}
],
"semantic_class_to_id": {
"TUBE": Value(dtype="int64"),
"OTHER_THING": Value(dtype="int64")
}
})
dummy_dataset = Dataset.from_list(data, features=features)
dummy_dataset.save_to_disk(HF_DATASET_PATH, split=SPLIT_NAME)
print("Dummy dataset created successfully!")
print("Please update config.xml if you want to use the 'OTHER_THING' label.")
print("It should look like this:")
print("""
<View>
<Image name="image" value="$image" />
<BrushLabels name="tag" toName="image">
<Label value="TUBE" background="rgba(255, 0, 0, 0.7)" />
<Label value="OTHER_THING" background="rgba(0, 255, 0, 0.7)" />
</BrushLabels>
</View>
""")
main()
Step 3: Importing into Label Studio
Start Label Studio:
Navigate to your project directory (where config.xml and label_studio_import folder are) in your terminal and run:
--allow-file-access is crucial if you're using file:// URLs in your JSON to allow Label Studio to load images from local paths.
my_image_segmentation_project is a name for your project.
Create/Configure Project:
Open http://localhost:8080 (or whatever address Label Studio gives you) in your browser.
Click "Create Project".
Give it a name.
Go to "Settings" -> "Labeling Interface" -> "Custom Template".
Copy the content of your config.xml into the XML editor and save.
Import Tasks:
Go to "Data" -> "Import".
Select "JSON".
Upload the label_studio_import/train_label_studio_tasks.json file you generated.
Explanation of the Script's Logic
convert_mask_to_rle(mask_array):
This function takes a 2D NumPy array representing a binary mask (where 1s are foreground and 0s are background).
It uses pycocotools.mask.encode which is the standard way to generate COCO RLE.
np.asfortranarray is necessary because pycocotools expects Fortran-contiguous arrays.
rle['counts'].decode('utf-8') is important because pycocotools returns bytes, but Label Studio (and JSON) expects a string.
main() function:
Loads Dataset:load_from_disk(HF_DATASET_PATH) loads your local Hugging Face dataset.
Output Directories: Creates label_studio_import/images to store the individual image files.
id_to_semantic_class: Creates a reverse mapping from category_id (integer) to class_name (string, e.g., "TUBE"). This is crucial for naming the brushlabels.
Iterates Examples: Loops through each example in your chosen dataset split.
Save Image: Each original image from the HF dataset is saved as a PNG in the output_images_dir.
Process Mask (label):
The label (mask) PIL Image is converted to a NumPy array.
np.unique(mask_np): This is key. It finds all unique pixel values in the mask, which correspond to the category_ids present in that specific image.
For each cat_id (skipping background 0):
A binary_mask is created for only that category. For example, if cat_id is 1, binary_mask will have 1 where mask_np was 1, and 0 everywhere else.
This binary_mask is then converted to RLE using convert_mask_to_rle.
A result dictionary is built for each brushlabels annotation.
original_width, original_height: Needed for RLE context.
value.rle: The generated RLE.
value.brushlabels: An array containing the class name (e.g., ["TUBE"]).
from_name, to_name, type: Match your Label Studio XML configuration.
id: A unique ID for each individual annotation (e.g., image_id_TUBE).
origin: "prefill": Tells Label Studio this came from a pre-annotation.
These result dictionaries are collected into predictions_results.
Construct Task: A complete Label Studio task dictionary is assembled for each image, containing the image data (as a file:// URL) and the predictions block with all the generated brushlabel results.
Save JSON: Finally, all tasks are saved to a JSON file (<split_name>_label_studio_tasks.json) in the OUTPUT_DIR.
This setup will allow you to quickly import your pre-annotated images into Label Studio, where you can review, correct, or add further annotations efficiently.