I got tired of writing the same 50 lines of OpenCV boilerplate every new project.
Every pipeline that uses SAM, U-Net, or any segmentation model hands you binary masks. YOLO training wants bounding box labels. The standard move is a custom script — cv2.findContours, normalize coordinates, handle edge cases, repeat. No reusable package existed that did this cleanly end-to-end.
So I built one and shipped it to PyPI.
The install
pip install segment-toolkit
What it does
segment-toolkit is a bidirectional pipeline between binary segmentation masks and YOLO bounding box labels.
Forward: binary mask to YOLO label (axis-aligned or rotated minimum-area box via cv2.minAreaRect)
Reverse: YOLO label back to binary mask
Visualizer: overlay bounding boxes on source images
Dataset split: auto train/test split with data.yaml output
Class mapping: batch conversion with CSV or JSON ground truth
CLI usage
Convert a single mask to a YOLO label:
segment-toolkit mask-to-yolo \
--image images/ISIC_0024310.jpg \
--mask mask/ISIC_0024310_segmentation.png \
--output-txt labels/ISIC_0024310.txt \
--class-id 4
Reconstruct the mask back from the label:
segment-toolkit yolo-to-mask \
--label labels/ISIC_0024310.txt \
--output-mask masks_reconstructed/ISIC_0024310_segmentation.png
Visualize the bounding box overlay:
segment-toolkit visualize \
--image images/ISIC_0024310.jpg \
--label labels/ISIC_0024310.txt \
--output visualization.png
Split into train/test with data.yaml:
segment-toolkit split \
--images images/ \
--labels labels/ \
--output dataset/ \
--ratio 0.8 \
--seed 42
Python API
from segment_toolkit import MaskToYoloConverter, YoloToMaskConverter
conv = MaskToYoloConverter(target_size=(640, 640), bbox_type="standard")
conv.convert_single(
image_path="images/ISIC_0024310.jpg",
mask_path="mask/ISIC_0024310_segmentation.png",
output_txt_path="labels/ISIC_0024310.txt",
class_id=4
)
Validated on
ISIC melanoma skin lesion segmentation and PlantVillage leaf disease. Both tested end-to-end: mask in, YOLO label out, mask reconstructed back, overlay rendered.
Repo
github.com/zkzkGamal/mask-to-yolo-toolkit
If you hit a bug or want a feature, open an issue.
Top comments (0)