""" Convert YOLO-segmentation-format labels (polygons) to YOLO-detection-format labels (bounding boxes), so a segmentation-labeled dataset can be dropped into a standard detection training pipeline. YOLO segmentation label line format: class_id x1 y1 x2 y2 x3 y3 ... xn yn (all normalized 0-1) YOLO detection label line format: class_id x_center y_center width height (all normalized 0-1) USAGE: Just set SRC_LABEL_DIR below to the folder containing the segmentation .txt files, and DST_LABEL_DIR to where you want the converted detection .txt files written. The script handles the rest -- multiple objects per file, multiple classes, etc. If you want to convert in place (overwrite the same files), set DST_LABEL_DIR equal to SRC_LABEL_DIR -- but a backup is strongly recommended first since this is a destructive format change. """ import os import shutil # ------------------------- CONFIG (edit these) ------------------------- SRC_LABEL_DIR = r"C:\Users\shrey\Downloads\project1.yolo26 (1)\valid\labels" # <-- drop your segmentation labels folder path here DST_LABEL_DIR = r"C:\Users\shrey\Downloads\dataset\labels_1" # <-- converted bbox labels will be written here # If True, skips any line that doesn't look like a valid polygon (odd number # of coordinates, too few points, etc.) instead of crashing the whole run. SKIP_INVALID_LINES = True # ------------------------------------------------------------------------- def polygon_to_bbox(coords): """coords: flat list [x1, y1, x2, y2, ...] normalized 0-1. Returns (xc, yc, w, h).""" xs = coords[0::2] ys = coords[1::2] x_min, x_max = min(xs), max(xs) y_min, y_max = min(ys), max(ys) x_center = (x_min + x_max) / 2 y_center = (y_min + y_max) / 2 width = x_max - x_min height = y_max - y_min return x_center, y_center, width, height def convert_file(src_path, dst_path): converted_lines = [] skipped = 0 with open(src_path) as f: for line in f: line = line.strip() if not line: continue parts = line.split() class_id = parts[0] coords = list(map(float, parts[1:])) if len(coords) < 6 or len(coords) % 2 != 0: # need at least 3 points (6 values) for a valid polygon skipped += 1 if not SKIP_INVALID_LINES: raise ValueError(f"Invalid polygon in {src_path}: {line}") continue xc, yc, w, h = polygon_to_bbox(coords) converted_lines.append(f"{class_id} {xc:.6f} {yc:.6f} {w:.6f} {h:.6f}") with open(dst_path, "w") as f: f.write("\n".join(converted_lines) + ("\n" if converted_lines else "")) return len(converted_lines), skipped def main(): if not os.path.isdir(SRC_LABEL_DIR): print(f"Source folder not found: {SRC_LABEL_DIR}") return os.makedirs(DST_LABEL_DIR, exist_ok=True) total_files = 0 total_boxes = 0 total_skipped = 0 for fname in os.listdir(SRC_LABEL_DIR): if not fname.endswith(".txt"): continue src_path = os.path.join(SRC_LABEL_DIR, fname) dst_path = os.path.join(DST_LABEL_DIR, fname) n_boxes, n_skipped = convert_file(src_path, dst_path) total_files += 1 total_boxes += n_boxes total_skipped += n_skipped print(f"Converted {total_files} label file(s).") print(f"Total bounding boxes written: {total_boxes}") if total_skipped: print(f"Skipped {total_skipped} invalid/malformed polygon line(s) -- check these manually if the count seems high.") print(f"\nOutput written to: {DST_LABEL_DIR}") print("Next: point your data.yaml / dataset folder at these converted labels " "(alongside the original images) before training.") if __name__ == "__main__": main()