Add the RLE conversion logic
- User
Add the RLE conversion logic
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Add the RLE conversion logic
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
You're absolutely right! My apologies for missing the RLE conversion logic in the first pass. Label Studio expects the RLE in a specific format (often similar to COCO RLE).
Let's integrate a robust RLE encoding function and refine the image handling for Label Studio.
rle_encode function is added that converts a 2D binary NumPy mask into the COCO-style RLE string.category_id from segments_info maps to the class names (e.g., "TUBE", "HANGER") based on the provided semantic_class_to_id structure. I'll make an assumption that category_id corresponds to the index if the semantic_class_to_id only lists names.import pyarrow as pa
import json
import os
from PIL import Image
import numpy as np
from datasets import load_dataset
import io # For handling image bytes if needed
# --- 1. RLE Encoding Function (COCO-style) ---
# Converts a binary mask (numpy array of 0s and 1s) to COCO-style RLE string
def rle_encode(mask: np.ndarray) -> str:
"""
Encodes a binary mask into COCO-style Run Length Encoding.
Args:
mask (np.ndarray): A 2D numpy array representing the binary mask (0s and 1s).
Expected shape (height, width).
Returns:
str: A space-separated string of integers representing the RLE.
Example: "0 4 209 252 57 27 ..." (length_of_zeros, length_of_ones, ...)
"""
# Ensure mask is flattened and treated as 0s and 1s
pixels = mask.flatten().astype(np.uint8)
# Pad with 0 at the start and end to correctly capture runs at boundaries
pixels = np.concatenate([[0], pixels, [0]])
# Find the indices where the value changes
# e.g., for [0,0,1,1,0], changes are at index 2 (0->1) and index 4 (1->0)
# The result `runs` will be the indices *after* the change.
# So, for [0,0,1,1,0,0], padded [0,0,0,1,1,0,0,0]
# np.where(pixels[1:] != pixels[:-1])[0] will give [2, 4] (end of first 0-run, end of first 1-run)
# This directly gives the cumulative lengths, starting from 0.
runs = np.where(pixels[1:] != pixels[:-1])[0]
# Calculate the lengths of each run.
# For `runs = [r0, r1, r2, ...]`, the lengths are `r0`, `r1-r0`, `r2-r1`, ...
# This creates the alternating lengths of 0s and 1s (or 1s and 0s).
# For example, [0,0,1,1,0,0] -> padded [0,0,0,1,1,0,0,0]
# runs = [2, 4]
# np.concatenate(([0], runs, [len(pixels)])) = [0, 2, 4, 8]
# np.diff(...) = [2, 2, 4] which means: 2 zeros, 2 ones, 4 zeros. This is correct for COCO.
run_lengths = np.diff(np.concatenate(([0], runs, [len(pixels)])))
return ' '.join(str(x) for x in run_lengths)
# --- 2. Configuration for Image Storage ---
# Directory to save the images for Label Studio to access
OUTPUT_IMAGE_DIR = "images_for_label_studio"
os.makedirs(OUTPUT_IMAGE_DIR, exist_ok=True)
# --- 3. Load Hugging Face Dataset ---
# Replace 'path/to/your/dataset' with the actual path to your Hugging Face dataset directory
# E.g., 'dataset_dir' if your structure is 'dataset_dir/train', 'dataset_dir/val' etc.
dataset_path = 'dataset' # Assuming your dataset is in a directory named 'dataset'
dataset = load_dataset(dataset_path)
# --- 4. Conversion Logic Per Split ---
def convert_split(split_name: str):
"""
Converts a single split of the Hugging Face dataset to Label Studio JSON format.
Args:
split_name (str): The name of the split (e.g., 'train', 'val', 'test').
Returns:
list: A list of dictionaries in Label Studio JSON format.
"""
print(f"Processing split: {split_name}...")
split_data = dataset[split_name]
# Load data_info.json for this split to get semantic class mapping
# Note: data_info.json is usually at the top level or shared,
# but based on your structure, it might be per split.
# Let's assume it's shared or accessible from any split's directory.
# Adjust this path if data_info.json is at the root `dataset_path/data_info.json`
data_info_path = os.path.join(dataset_path, split_name, 'data_info.json')
if not os.path.exists(data_info_path):
# Fallback if data_info.json is at the root, or assume it's loaded once
data_info_path = os.path.join(dataset_path, 'data_info.json') # Try root level
if not os.path.exists(data_info_path):
raise FileNotFoundError(f"data_info.json not found at {data_info_path} or {os.path.join(dataset_path, split_name, 'data_info.json')}")
with open(data_info_path, 'r') as f:
data_info = json.load(f)
# Extract semantic class to ID mapping
# Assuming 'semantic_class_to_id' maps class names to their numerical IDs
# Based on your example: {"TUBE": {"dtype": "int64", "_type": "Value"}}
# This structure is unusual for direct ID mapping.
# Let's assume `category_id` from `segments_info` directly corresponds to
# an integer ID, and we need to map that ID back to a class name.
# If `semantic_class_to_id` only provides names without IDs,
# we'll create a mapping assuming `category_id` 0 -> first sorted name, 1 -> second, etc.
semantic_class_names = list(data_info['features']['semantic_class_to_id'].keys())
semantic_class_names.sort() # Ensure consistent order for mapping by index
category_id_to_name = {}
# If `semantic_class_to_id` were {"TUBE": 0, "HANGER": 1}, we'd reverse it:
# category_id_to_name = {v: k for k, v in data_info['features']['semantic_class_to_id'].items()}
# Given the example {"TUBE": {"dtype": "int64", "_type": "Value"}},
# the most reasonable guess is that category_id `N` corresponds to the N-th class name
# in some predefined order (e.g., alphabetical).
# If your dataset's documentation specifies an explicit mapping, use that instead.
for i, name in enumerate(semantic_class_names):
category_id_to_name[i] = name
if not category_id_to_name:
print("Warning: semantic_class_to_id mapping is empty or not in expected format. Labels might be incorrect.")
label_studio_format = []
for idx, example in enumerate(split_data):
# --- Handle Image ---
# The 'image' feature is a PIL Image object
pil_image = example['image'].convert('RGB') # Ensure RGB format
# Define path to save the image
# Use a unique name for each image, e.g., split_name_index.png
image_filename = f"{split_name}_{idx:05d}.png" # e.g., train_00000.png
saved_image_path = os.path.join(OUTPUT_IMAGE_DIR, image_filename)
pil_image.save(saved_image_path)
# Label Studio will load images from this path (relative to where you import the JSON)
# If you're importing a local directory, you'd specify the path relative to that directory.
# Here, we're using a path relative to the script's execution directory.
ls_image_path = os.path.join(OUTPUT_IMAGE_DIR, image_filename)
# --- Handle Annotations (Segments) ---
segment_predictions = []
if 'segments_info' in example and example['segments_info']:
# The 'label' feature is assumed to be a segmentation mask PIL Image
# where pixel values correspond to category_ids or instance_ids
# Convert PIL mask to numpy array for processing
mask_image_np = np.array(example['label'])
for segment_idx, segment in enumerate(example['segments_info']):
category_id = segment['category_id']
# Get the binary mask for this specific segment
# Assuming mask_image_np pixels are category_ids
segment_mask_binary = (mask_image_np == category_id).astype(np.uint8)
# Ensure mask is not empty before encoding (might happen if segment info is wrong)
if segment_mask_binary.sum() == 0:
print(f"Warning: Segment {segment_idx} for image {idx} in {split_name} split has an empty mask. Skipping.")
continue
# Encode the binary mask to RLE
rle_string = rle_encode(segment_mask_binary)
# Get the label name for the category ID
label_name = category_id_to_name.get(category_id, f"UNKNOWN_CLASS_{category_id}")
segment_predictions.append({
"original_width": pil_image.width,
"original_height": pil_image.height,
"image_rotation": 0, # Assuming no rotation in source data
"value": {
"format": "rle",
"rle": rle_string,
"brushlabels": [label_name] # Label Studio expects a list of labels
},
"id": f"segment_{idx}_{segment_idx}_{segment['id']}", # Unique ID for this annotation result
"from_name": "tag", # Name of the Label Studio control tag (e.g., <BrushLabels name="tag" ...>)
"to_name": "image", # Name of the object tag (e.g., <Image name="image" ...>)
"type": "brushlabels", # Type of annotation (e.g., "brushlabels", "rectanglelabels", etc.)
"origin": "manual" # Or "prediction" if these are model predictions
})
else:
print(f"Warning: No 'segments_info' found for image {idx} in {split_name} split. No annotations added.")
# --- Construct Label Studio Task JSON ---
label_studio_format.append({
"id": idx, # Unique ID for the task
"data": {
"image": ls_image_path # Path to the image file
},
"predictions": [{ # List of prediction objects
"model_version": "prelabeled_dataset", # Optional: Name of your pre-labeling source
"result": segment_predictions # List of individual annotation results
}]
})
return label_studio_format
# --- 5. Convert and Save Each Split ---
all_label_studio_data = {}
for split_name in dataset.keys(): # Iterates through 'train', 'val', 'test'
converted_data = convert_split(split_name)
all_label_studio_data[split_name] = converted_data
# Save each split to its own JSON file
output_json_filename = f"{split_name}_label_studio_tasks.json"
with open(output_json_filename, 'w') as f:
json.dump(converted_data, f, indent=4)
print(f"Saved {len(converted_data)} tasks for {split_name} to {output_json_filename}")
print(f"\nAll images saved to: {os.path.abspath(OUTPUT_IMAGE_DIR)}")
print("Conversion complete. You can now import the generated JSON files into Label Studio.")
print("When importing, make sure to configure Label Studio to access the image files in the 'images_for_label_studio' directory.")
hf_to_ls.py).dataset_path: Change 'dataset' in dataset = load_dataset(dataset_path) to the actual path of your Hugging Face dataset directory.python hf_to_ls.pytrain_label_studio_tasks.json, val_label_studio_tasks.json, test_label_studio_tasks.json in the same directory as your script.images_for_label_studio will be created, containing all the saved image files.BrushLabels control tag name matches the from_name in the JSON (e.g., tag).Image object tag name matches the to_name (e.g., image).semantic_class_to_id categories.<View>
<Image name="image" value="$image"/>
<BrushLabels name="tag" toName="image">
<Label value="TUBE" background="rgba(255, 0, 0, 0.7)"/>
<Label value="HANGER" background="rgba(0, 255, 0, 0.7)"/>
<!-- Add other labels as needed -->
</BrushLabels>
</View>
train_label_studio_tasks.json).label-studio start --data-dir)" or "Cloud Storage" if you're hosting them.
label-studio start --data-dir <path_to_parent_of_OUTPUT_IMAGE_DIR> (e.g., if your script is in /my_project and images_for_label_studio is in /my_project/images_for_label_studio, then data-dir would be /my_project).images_for_label_studio directory.Your images should now appear in Label Studio with the pre-existing segmentation masks and labels!