Add trained steel ROI gate and hybrid validation
Browse filesFiles changed (7)
187 unmodified lines188189190191192193194195196197198199200201202203204205187 unmodified linesroi_area_ratio=roi_area_ratio,)return SurfaceGateResult(is_steel=True,confidence=float(best_candidate["confidence"]),mode="detector",label=str(best_candidate["label"]),reason=(f"Steel-surface detector localized an inspection ROI with {float(best_candidate['confidence']):.0%} confidence."),metrics={"boxes_detected": float(len(candidates)),"roi_area_ratio": round(roi_area_ratio, 4),"selector_score": round(float(best_candidate["selector_score"]), 4),},roi_bbox=best_candidate["bbox"],roi_area_ratio=roi_area_ratio,187 unmodified lines188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230187 unmodified linesroi_area_ratio=roi_area_ratio,)roi_x, roi_y, roi_width, roi_height = best_candidate["bbox"]roi_image = image[roi_y:roi_y + roi_height, roi_x:roi_x + roi_width]heuristic_result = self._evaluate_with_heuristic(roi_image)if not heuristic_result.is_steel:return SurfaceGateResult(is_steel=False,confidence=float(best_candidate["confidence"]),mode="detector+heuristic",label=str(best_candidate["label"]),reason=("Frame skipped because the localized ROI did not pass the steel-surface texture validation step. ""Reduce background content and center the actual material."),metrics={"boxes_detected": float(len(candidates)),"roi_area_ratio": round(roi_area_ratio, 4),"selector_score": round(float(best_candidate["selector_score"]), 4),**heuristic_result.metrics,},roi_bbox=best_candidate["bbox"],roi_area_ratio=roi_area_ratio,)return SurfaceGateResult(is_steel=True,confidence=float(best_candidate["confidence"]),mode="detector+heuristic",label=str(best_candidate["label"]),reason=(f"Steel-surface detector localized an inspection ROI with {float(best_candidate['confidence']):.0%} confidence, ""and the ROI passed surface-texture validation."),metrics={"boxes_detected": float(len(candidates)),"roi_area_ratio": round(roi_area_ratio, 4),"selector_score": round(float(best_candidate["selector_score"]), 4),**heuristic_result.metrics,},roi_bbox=best_candidate["bbox"],roi_area_ratio=roi_area_ratio,
123version https://git-lfs.github.com/spec/v1oid sha256:fcf2d6d9662e8ee5765db2d27f313b4155e3688ea946f335af9dd01e4fff91b4size 543644233 unmodified lines3435363738394013 unmodified lines5455565758596033 unmodified linesAutomatic non-steel/background source:- Imagenette via Hugging Face DatasetsThis avoids making you manually collect a non-steel dataset.13 unmodified linesvenv/bin/python training/prepare_surface_gate_dataset.py```This default mode is the fastest path because it avoids downloading the larger Severstal archive.If you want a stronger detector after the first run, rebuild with Severstal included:33 unmodified lines34353637383940414213 unmodified lines5657585960616263646566676833 unmodified linesAutomatic non-steel/background source:- `torchvision` datasets downloaded automatically- default quick path: `CIFAR10`- optional stronger but heavier path: `STL10`This avoids making you manually collect a non-steel dataset.13 unmodified linesvenv/bin/python training/prepare_surface_gate_dataset.py```This default mode is the fastest path because it avoids the larger Severstal archive and uses `CIFAR10` as an automatic non-steel source.If you want stronger natural-scene negatives later:```bashvenv/bin/python training/prepare_surface_gate_dataset.py --negative-source stl10```If you want a stronger detector after the first run, rebuild with Severstal included:
2 unmodified lines34567892 unmodified lines12131415161718192021222324252627282946 unmodified lines767778798081105 unmodified lines18718818919019119219319419519619719819920020120220320420587 unmodified lines2932942952962972982999 unmodified lines30931031131231331431527 unmodified lines3433443453463473482 unmodified linesimport argparseimport jsonimport randomimport shutilimport zipfilefrom pathlib import Path2 unmodified linesimport yamlfrom huggingface_hub import snapshot_downloadfrom tqdm import tqdmtry:from datasets import load_datasetexcept Exception as exc: # pragma: no cover - import guard for guidanceraise SystemExit("The `datasets` package is required for this script. Install training/requirements.txt first.") from excSEVERSTAL_REPO = "rohanath/severstal-steel-detection"NEU_REPO = "LiuErXiao/NEU_valid"IMAGENETTE_REPO = "frgfm/imagenette"def parse_args() -> argparse.Namespace:46 unmodified linesdefault=1.0,help="How many pure background negatives to generate per steel image.",)parser.add_argument("--seed", type=int, default=42)return parser.parse_args()105 unmodified linescv2.imwrite(str(path), image)def export_negative_pool(target_dir: Path, limit: int, rng: random.Random) -> list[Path]:dataset = load_dataset(IMAGENETTE_REPO, "160px")samples = list(dataset["train"]) + list(dataset["validation"])rng.shuffle(samples)output_paths: list[Path] = []for index, sample in enumerate(samples[:limit]):image = cv2.cvtColor(np.array(sample["image"]), cv2.COLOR_RGB2BGR)destination = target_dir / f"imagenette_{index:05d}.jpg"save_image(destination, center_crop_and_resize(image, 640))output_paths.append(destination)return output_pathsdef build_split(87 unmodified linesensure_clean_dir(labels_dir)neu_raw = extract_first_zip(NEU_REPO, raw_root / "neu")negative_dir = raw_root / "imagenette"ensure_clean_dir(negative_dir)steel_paths: list[Path] = []9 unmodified linesif not steel_paths:raise RuntimeError("No steel images were collected for the detector dataset.")negative_paths = export_negative_pool(negative_dir, args.max_negatives, rng)if not negative_paths:raise RuntimeError("No negative background images were collected.")27 unmodified lines{"steel_sources": len(steel_paths),"negative_pool": len(negative_paths),"splits": summary,"dataset_yaml": str(yaml_path),},2 unmodified lines3456782 unmodified lines111213141516171819202146 unmodified lines686970717273747576777879105 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722887 unmodified lines3163173183193203213229 unmodified lines33233333433533633733833934034134234327 unmodified lines3713723733743753763772 unmodified linesimport argparseimport jsonimport randomimport zipfilefrom pathlib import Path2 unmodified linesimport yamlfrom huggingface_hub import snapshot_downloadfrom tqdm import tqdmfrom torchvision.datasets import CIFAR10, STL10SEVERSTAL_REPO = "rohanath/severstal-steel-detection"NEU_REPO = "LiuErXiao/NEU_valid"def parse_args() -> argparse.Namespace:46 unmodified linesdefault=1.0,help="How many pure background negatives to generate per steel image.",)parser.add_argument("--negative-source",default="cifar10",choices=["cifar10", "stl10", "auto"],help="Automatic non-steel image source. `cifar10` is the fastest default.",)parser.add_argument("--seed", type=int, default=42)return parser.parse_args()105 unmodified linescv2.imwrite(str(path), image)def export_negative_pool(target_dir: Path,limit: int,rng: random.Random,negative_source: str,) -> tuple[list[Path], str]:source_loaders = {"cifar10": lambda root: CIFAR10(root=str(root), train=True, download=True),"stl10": lambda root: STL10(root=str(root), split="train", download=True),}if negative_source == "auto":datasets_to_try = [("cifar10", source_loaders["cifar10"]), ("stl10", source_loaders["stl10"])]else:datasets_to_try = [(negative_source, source_loaders[negative_source])]last_error: Exception | None = Nonefor dataset_name, loader in datasets_to_try:try:dataset = loader(target_dir / "_torchvision_cache")samples = list(range(len(dataset)))rng.shuffle(samples)output_paths: list[Path] = []for index, sample_index in enumerate(samples[:limit]):sample_image, _ = dataset[sample_index]image = cv2.cvtColor(np.array(sample_image), cv2.COLOR_RGB2BGR)destination = target_dir / f"{dataset_name}_{index:05d}.jpg"save_image(destination, center_crop_and_resize(image, 640))output_paths.append(destination)if output_paths:return output_paths, dataset_nameexcept Exception as exc: # pragma: no cover - download/runtime fallbacklast_error = excraise RuntimeError("Unable to download an automatic negative-image source via torchvision.") from last_errordef build_split(87 unmodified linesensure_clean_dir(labels_dir)neu_raw = extract_first_zip(NEU_REPO, raw_root / "neu")negative_dir = raw_root / "negatives"ensure_clean_dir(negative_dir)steel_paths: list[Path] = []9 unmodified linesif not steel_paths:raise RuntimeError("No steel images were collected for the detector dataset.")negative_paths, negative_source = export_negative_pool(negative_dir,args.max_negatives,rng,args.negative_source,)if not negative_paths:raise RuntimeError("No negative background images were collected.")27 unmodified lines{"steel_sources": len(steel_paths),"negative_pool": len(negative_paths),"negative_source": negative_source,"splits": summary,"dataset_yaml": str(yaml_path),},
1234datasetshuggingface_hubPillowPyYAML123huggingface_hubPillowPyYAML
22 unmodified lines2324252627282912 unmodified lines42434445464748495051525322 unmodified lines)parser.add_argument("--epochs", type=int, default=18)parser.add_argument("--imgsz", type=int, default=512)parser.add_argument("--batch", default=16)parser.add_argument("--device", default="")parser.add_argument("--workers", type=int, default=4)parser.add_argument("--project", default="training/runs")12 unmodified linesif not data_path.exists():raise FileNotFoundError(f"Dataset YAML not found: {data_path}")model = YOLO(args.model)results = model.train(data=str(data_path),epochs=args.epochs,imgsz=args.imgsz,batch=args.batch,device=args.device or None,workers=args.workers,project=args.project,22 unmodified lines2324252627282912 unmodified lines424344454647484950515253545522 unmodified lines)parser.add_argument("--epochs", type=int, default=18)parser.add_argument("--imgsz", type=int, default=512)parser.add_argument("--batch", type=float, default=16)parser.add_argument("--device", default="")parser.add_argument("--workers", type=int, default=4)parser.add_argument("--project", default="training/runs")12 unmodified linesif not data_path.exists():raise FileNotFoundError(f"Dataset YAML not found: {data_path}")batch = int(args.batch) if float(args.batch).is_integer() else float(args.batch)model = YOLO(args.model)results = model.train(data=str(data_path),epochs=args.epochs,imgsz=args.imgsz,batch=batch,device=args.device or None,workers=args.workers,project=args.project,
123version https://git-lfs.github.com/spec/v1oid sha256:0ebbc80d4a7680d14987a577cd21342b65ecfd94632bd9a8da63ae6417644ee1size 5613764inspection/surface_gate.py+27-2
models/steel_surface_detector.ptAdded+3
training/README.md+10-2
training/prepare_surface_gate_dataset.py+53-24
training/requirements.txt-1
training/train_surface_gate_detector.py+4-2
yolo11n.ptAdded+3