File size: 8,335 Bytes
fe69e84 | 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | #!/usr/bin/env python3
"""
prepare_dataset.py — turn the downloaded raw datasets into the train/val/test
folder tree that backend/train.py expects.
Pipeline:
1. Read MAPPING below (raw subfolder -> CropGuard class key).
2. Copy every matched image into <out>_flat/<class>/ .
3. Split each class 70/15/15 into <out>/train|val|test/<class>/ .
4. Print a per-class count so you can see which classes are thin.
IMPORTANT — you must edit the SOURCE PATHS in MAPPING to match where you
actually unzipped each dataset. Mirror folder names differ slightly, so adjust
the left-hand paths (relative to --raw) until they point at real folders.
Usage:
python prepare_dataset.py --raw ./raw_downloads --out ./data
python prepare_dataset.py --raw ./raw_downloads --out ./data --check # report only, copy nothing
"""
import argparse, os, random, shutil
from collections import defaultdict
random.seed(42)
IMG_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
# ----------------------------------------------------------------------------
# MAPPING: { class_key : [ list of raw subfolders (relative to --raw) ] }
# Multiple source folders can feed one class; edit paths to match your unzip.
# Folders that don't exist are simply skipped (with a warning), so it's safe to
# fill in only the datasets you have downloaded so far.
# ----------------------------------------------------------------------------
MAPPING = {
# ---- Maize (CCMT + PlantVillage) ----
"maize_healthy": ["CCMT/Maize/healthy", "plantvillage/Corn_(maize)___healthy"],
"maize_gls": ["CCMT/Maize/leaf spot", "plantvillage/Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot"],
"maize_nclb": ["CCMT/Maize/leaf blight", "plantvillage/Corn_(maize)___Northern_Leaf_Blight"],
"maize_rust": ["plantvillage/Corn_(maize)___Common_rust_"],
"maize_msv": ["CCMT/Maize/streak virus"],
"maize_faw": ["CCMT/Maize/fall armyworm"],
# ---- Cassava (Cassava-Kaggle + CCMT) ----
"cassava_healthy":["cassava/healthy", "CCMT/Cassava/healthy"],
"cassava_cmd": ["cassava/cmd", "CCMT/Cassava/mosaic"],
"cassava_cbsd": ["cassava/cbsd"],
"cassava_cbb": ["cassava/cbb", "CCMT/Cassava/bacterial blight"],
# ---- Tomato (CCMT + PlantVillage) ----
"tomato_healthy": ["CCMT/Tomato/healthy", "plantvillage/Tomato___healthy"],
"tomato_early": ["plantvillage/Tomato___Early_blight"],
"tomato_late": ["plantvillage/Tomato___Late_blight", "CCMT/Tomato/leaf blight"],
"tomato_wilt": ["CCMT/Tomato/verticillium wilt"],
"tomato_septoria":["plantvillage/Tomato___Septoria_leaf_spot", "CCMT/Tomato/septoria"],
"tomato_tylcv": ["plantvillage/Tomato___Tomato_Yellow_Leaf_Curl_Virus", "CCMT/Tomato/leaf curl"],
# ---- Cocoa (KaraAgroAI + Kaggle cocoa) ----
"cocoa_healthy": ["cocoa/healthy"],
"cocoa_blackpod": ["cocoa/black_pod"],
"cocoa_cssvd": ["cocoa/cssvd"],
"cocoa_capsid": ["LOCAL/cocoa_capsid"], # collect locally
# ---- Cashew (CCMT) ----
"cashew_healthy": ["CCMT/Cashew/healthy"],
"cashew_anthracnose":["CCMT/Cashew/anthracnose"],
"cashew_gumosis": ["CCMT/Cashew/gummosis"],
"cashew_leafminer": ["CCMT/Cashew/leaf miner"],
# ---- Plantain (BananaLSD + local) ----
"plantain_healthy": ["bananalsd/healthy"],
"plantain_sigatoka": ["bananalsd/sigatoka"],
"plantain_bbtv": ["LOCAL/plantain_bbtv"], # collect locally
"plantain_panama": ["LOCAL/plantain_panama"], # collect locally
# ---- Yam (local) ----
"yam_healthy": ["LOCAL/yam_healthy"],
"yam_anthracnose":["LOCAL/yam_anthracnose"],
"yam_mosaic": ["LOCAL/yam_mosaic"],
# ---- Pepper (PlantVillage + chili anthracnose/local) ----
"pepper_healthy": ["plantvillage/Pepper,_bell___healthy"],
"pepper_bacterialspot":["plantvillage/Pepper,_bell___Bacterial_spot"],
"pepper_anthracnose": ["LOCAL/pepper_anthracnose"],
# ---- Cowpea (local) ----
"cowpea_healthy": ["LOCAL/cowpea_healthy"],
"cowpea_blight": ["LOCAL/cowpea_blight"],
"cowpea_mosaic": ["LOCAL/cowpea_mosaic"],
"cowpea_cercospora":["LOCAL/cowpea_cercospora"],
# ---- Groundnut (Sasmal) ----
"groundnut_healthy": ["groundnut/HEALTHY"],
"groundnut_leafspot":["groundnut/LEAF SPOT (EARLY AND LATE)"],
"groundnut_rosette": ["groundnut/ROSETTE"],
"groundnut_rust": ["groundnut/RUST"],
# ---- Rice (Sethy + healthy source/local) ----
"rice_healthy": ["LOCAL/rice_healthy"],
"rice_blast": ["rice/Blast"],
"rice_blb": ["rice/Bacterialblight"],
"rice_brownspot": ["rice/Brownspot"],
# ---- Okra (local) ----
"okra_healthy": ["LOCAL/okra_healthy"],
"okra_yvmv": ["LOCAL/okra_yvmv"],
"okra_leafspot":["LOCAL/okra_leafspot"],
# ---- Garden egg (local) ----
"gardenegg_healthy": ["LOCAL/gardenegg_healthy"],
"gardenegg_wilt": ["LOCAL/gardenegg_wilt"],
"gardenegg_leafspot":["LOCAL/gardenegg_leafspot"],
# ---- Mango (MangoLeafBD) ----
"mango_healthy": ["mangoleafbd/Healthy"],
"mango_anthracnose": ["mangoleafbd/Anthracnose"],
"mango_bacterialspot":["mangoleafbd/Bacterial Canker"],
}
def list_images(folder):
if not os.path.isdir(folder):
return []
out = []
for root, _, files in os.walk(folder):
for f in files:
if f.lower().endswith(IMG_EXT):
out.append(os.path.join(root, f))
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--raw", default="./raw_downloads")
ap.add_argument("--out", default="./data")
ap.add_argument("--check", action="store_true", help="report counts only, copy nothing")
ap.add_argument("--val", type=float, default=0.15)
ap.add_argument("--test", type=float, default=0.15)
args = ap.parse_args()
flat = args.out + "_flat"
counts = {}
missing = []
for cls, sources in MAPPING.items():
imgs = []
for s in sources:
p = os.path.join(args.raw, s)
found = list_images(p)
if not found and not s.startswith("LOCAL/"):
missing.append((cls, s))
imgs += found
counts[cls] = len(imgs)
if args.check:
continue
# copy into flat/<cls>/
dst = os.path.join(flat, cls)
os.makedirs(dst, exist_ok=True)
for i, src in enumerate(imgs):
ext = os.path.splitext(src)[1].lower()
shutil.copy2(src, os.path.join(dst, f"{cls}_{i:05d}{ext}"))
# ---- split flat -> train/val/test ----
if not args.check:
for cls in MAPPING:
files = list_images(os.path.join(flat, cls))
random.shuffle(files)
n = len(files)
n_test = int(n * args.test)
n_val = int(n * args.val)
buckets = {
"test": files[:n_test],
"val": files[n_test:n_test + n_val],
"train": files[n_test + n_val:],
}
for split, fs in buckets.items():
d = os.path.join(args.out, split, cls)
os.makedirs(d, exist_ok=True)
for f in fs:
shutil.copy2(f, os.path.join(d, os.path.basename(f)))
# ---- report ----
print("\nPer-class image counts:")
weak = []
for cls in MAPPING:
c = counts[cls]
tag = ""
if c == 0:
tag = " <-- EMPTY (fix the source path, or collect images)"
weak.append(cls)
elif c < 100:
tag = " <-- thin (<100); model will be weak here"
weak.append(cls)
print(f" {cls:<22} {c:>6}{tag}")
print(f"\nTotal images: {sum(counts.values())}")
if missing:
print(f"\n{len(missing)} mapped source folder(s) not found — edit the paths in MAPPING:")
for cls, s in missing[:40]:
print(f" {cls}: {s}")
if weak:
print(f"\n{len(weak)} class(es) empty or thin — collect local images for these before relying on them.")
if args.check:
print("\n(--check: nothing was copied)")
else:
print(f"\nDone. Train with:\n cd backend && python train.py --data ../{os.path.basename(args.out)} --arch efficientnet")
if __name__ == "__main__":
main()
|