File size: 2,708 Bytes
57ade7d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import csv\n",
"import random\n",
"\n",
"def generate_dataset_csv(images_dir, masks_dir, output_file, train_ratio=0.7):\n",
" # Get list of images and sort them\n",
" images = sorted([f for f in os.listdir(images_dir) if f.endswith('.png')])\n",
" \n",
" # Create pairs of image paths and corresponding mask paths\n",
" data = []\n",
" for img in images:\n",
" # Get corresponding mask name by adding '_mask' before .png\n",
" mask = img.replace('.png', '_mask.png')\n",
" \n",
" # Create full paths\n",
" img_path = os.path.join(images_dir, img)\n",
" mask_path = os.path.join(masks_dir, mask)\n",
" \n",
" # Verify both files exist before adding\n",
" if os.path.exists(img_path) and os.path.exists(mask_path):\n",
" data.append([img_path, mask_path])\n",
" \n",
" # Randomly split into training and validation sets\n",
" random.seed(42) # for reproducibility\n",
" random.shuffle(data)\n",
" split_idx = int(len(data) * train_ratio)\n",
" \n",
" # Assign splits\n",
" for i in range(len(data)):\n",
" split = 'training' if i < split_idx else 'val'\n",
" data[i].extend([split, 0]) # add split and fold (0 for all)\n",
" \n",
" # Write to CSV\n",
" with open(output_file, 'w', newline='') as f:\n",
" writer = csv.writer(f)\n",
" writer.writerow(['imgs', 'labels', 'split', 'fold']) # header\n",
" writer.writerows(data)\n",
"\n",
"# Example usage\n",
"images_dir = '/l/users/sarim.hashmi/for_the_little_interns/the_experiments/drive_dataset/dataset_drive/images'\n",
"masks_dir = '/l/users/sarim.hashmi/for_the_little_interns/the_experiments/drive_dataset/dataset_drive/masks'\n",
"output_file = 'data_split.csv'\n",
"\n",
"generate_dataset_csv(images_dir, masks_dir, output_file)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "AI702",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|