#!/bin/bash # Get script dir SCRIPT_DIR=$(cd $(dirname $0); pwd) LABELME_DIR=$SCRIPT_DIR/../export_annotated COCO_DIR=$SCRIPT_DIR/../export_coco # Create necessary directories mkdir -p $COCO_DIR/train mkdir -p $COCO_DIR/val mkdir -p $COCO_DIR/annotations # Clean train, val, and annotations directories by removing all files rm -rf $COCO_DIR/train/* rm -rf $COCO_DIR/val/* rm -rf $COCO_DIR/annotations/* # Determine the number of files for validation (20%) LABELME_FILES=$(find "$LABELME_DIR" -name "*.json") NUM_FILES=$(echo "$LABELME_FILES" | wc -l) VAL_COUNT=$(echo "$NUM_FILES * 0.2" | bc | awk '{print int($1+0.5)}') # Shuffle files and split into train and val sets SHUFFLED_FILES=$(echo "$LABELME_FILES" | shuf) VAL_FILES=$(echo "$SHUFFLED_FILES" | head -n $VAL_COUNT) TRAIN_FILES=$(echo "$SHUFFLED_FILES" | tail -n +$(($VAL_COUNT + 1))) # Copy validation files and their corresponding images to val echo "$VAL_FILES" | while read -r val_file; do cp "$val_file" "$COCO_DIR/val/" # Copy the corresponding image file (assuming it has the same base name) image_file="${val_file%.json}.png" # Change the extension to match your images if [[ -f "$image_file" ]]; then cp "$image_file" "$COCO_DIR/val/" fi done # Copy training files and their corresponding images to train echo "$TRAIN_FILES" | while read -r train_file; do cp "$train_file" "$COCO_DIR/train/" # Copy the corresponding image file (assuming it has the same base name) image_file="${train_file%.json}.png" # Change the extension to match your images if [[ -f "$image_file" ]]; then cp "$image_file" "$COCO_DIR/train/" fi done # Convert Labelme JSON to COCO format for train and val labelme2coco $COCO_DIR/train $COCO_DIR/annotations mv $COCO_DIR/annotations/dataset.json $COCO_DIR/annotations/train.json labelme2coco $COCO_DIR/val $COCO_DIR/annotations mv $COCO_DIR/annotations/dataset.json $COCO_DIR/annotations/val.json # Remove the Labelme JSON files from train and val directories after conversion find $COCO_DIR/train -name "*.json" -type f -delete find $COCO_DIR/val -name "*.json" -type f -delete echo "Conversion to COCO format completed, and JSON files have been deleted from train and val directories."