Converting Hugging Face Dataset to Label Studio Format
To convert your Hugging Face dataset (in Arrow format) to a Label Studio-compatible JSON format for pre-labeled images, you'll need to:
- Load the dataset
- Extract the image and annotation data
- Transform it into Label Studio's expected format
Here's a step-by-step solution:
Step 1: Install Required Packages
pip install datasets pyarrow pillow
Step 2: Conversion Script
import json
from datasets import load_from_disk
from pathlib import Path
import base64
from PIL import Image
import io
def convert_hf_to_labelstudio(dataset_path, output_path):
# Load the Hugging Face dataset
dataset = load_from_disk(dataset_path)
# Initialize Label Studio format
label_studio_data = []
for split in ['train', 'val', 'test']:
if split not in dataset:
continue
split_data = dataset[split]
for idx, item in enumerate(split_data):
# Create Label Studio item structure
ls_item = {
"id": idx + 1, # Label Studio expects 1-based indexing
"data": {
"image": None # Will be replaced with image data
},
"annotations": [{
"result": [],
"completed_by": 1 # Default user ID
}]
}
# Handle image data
image = item['image']
if isinstance(image, dict) and 'bytes' in image:
# If image is in bytes format
image_bytes = image['bytes']
else:
# Convert PIL image to bytes
buffered = io.BytesIO()
image.save(buffered, format="PNG")
image_bytes = buffered.getvalue()
# Convert image to base64
image_base64 = base64.b64encode(image_bytes).decode('utf-8')
ls_item['data']['image'] = f"data:image/png;base64,{image_base64}"
# Handle annotations (assuming semantic segmentation masks)
if 'label' in item:
label = item['label']
if isinstance(label, dict) and 'bytes' in label:
# If label is in bytes format
label_bytes = label['bytes']
label_image = Image.open(io.BytesIO(label_bytes))
else:
label_image = label
# Convert label to RLE format expected by Label Studio
# This is a simplified version - you may need to adjust based on your exact format
width, height = label_image.size
rle = []
current_val = None
count = 0
for y in range(height):
for x in range(width):
pixel = label_image.getpixel((x, y))
if pixel != current_val:
if current_val is not None:
rle.append(count)
current_val = pixel
count = 1
else:
count += 1
if current_val is not None:
rle.append(count)
# Add annotation to result
annotation = {
"original_width": width,
"original_height": height,
"image_rotation": 0,
"value": {
"format": "rle",
"rle": rle,
"brushlabels": ["TUBE"] # Adjust based on your classes
},
"id": f"annotation_{idx}",
"from_name": "tag",
"to_name": "image",
"type": "brushlabels",
"origin": "manual"
}
ls_item['annotations'][0]['result'].append(annotation)
label_studio_data.append(ls_item)
# Save to output file
with open(output_path, 'w') as f:
json.dump(label_studio_data, f, indent=2)
# Usage
dataset_path = "path/to/your/dataset"
output_path = "label_studio_import.json"
convert_hf_to_labelstudio(dataset_path, output_path)