split / scratch /test_sahi_sample.py
FaustDerLegende's picture
Upload folder using huggingface_hub (part 61)
11a414e verified
Raw History Blame Contribute Delete
4.82 kB
"""Test Sliced Patch Inference (SAHI) on a sample of images to verify detection recall across classes."""
import os
from pathlib import Path
import torch
import torchvision
from torchvision.ops import nms
import numpy as np
from PIL import Image
cache_dir = Path("data/cache").resolve()
cache_dir.mkdir(parents=True, exist_ok=True)
os.environ["TORCH_HOME"] = str(cache_dir)
os.environ["HF_HOME"] = str(cache_dir)
from ultralytics import YOLOWorld
CLASS_NAMES = [
"cpu_socket",
"gold_finger",
"ic_chip",
"tantalum_capacitor",
"forcibly_desoldered_pad",
"factory_unpopulated_pad",
"occluded_region",
]
CLASS_PROMPTS = [
"CPU socket",
"gold finger edge connector",
"microchip",
"tantalum capacitor",
"desoldered solder pad",
"unpopulated solder pad",
"heatsink shield",
]
def apply_nms(boxes_list: list, iou_threshold: float = 0.45) -> list:
if not boxes_list:
return []
boxes_t = torch.tensor([b[:4] for b in boxes_list], dtype=torch.float32)
scores_t = torch.tensor([b[4] for b in boxes_list], dtype=torch.float32)
cls_t = torch.tensor([b[5] for b in boxes_list], dtype=torch.int64)
keep_indices = []
unique_classes = torch.unique(cls_t)
for c in unique_classes:
c_mask = (cls_t == c)
c_idxs = torch.where(c_mask)[0]
c_boxes = boxes_t[c_idxs]
c_scores = scores_t[c_idxs]
c_keep = nms(c_boxes, c_scores, iou_threshold)
keep_indices.extend(c_idxs[c_keep].tolist())
return [boxes_list[i] for i in keep_indices]
def predict_sliced(model, img_path: Path, conf_threshold: float = 0.02, slice_size: int = 640, overlap: float = 0.2, iou_threshold: float = 0.45):
with Image.open(img_path) as img:
img_w, img_h = img.size
np_img = np.array(img.convert("RGB"))
all_boxes = []
# 1. Full Image Pass
res_full = model.predict(np_img, conf=conf_threshold, verbose=False)
if res_full and len(res_full) > 0 and res_full[0].boxes is not None and len(res_full[0].boxes) > 0:
boxes_xyxy = res_full[0].boxes.xyxy.cpu().numpy()
confs = res_full[0].boxes.conf.cpu().numpy()
cls_ids = res_full[0].boxes.cls.cpu().numpy().astype(int)
for (x1, y1, x2, y2), c, cls_id in zip(boxes_xyxy, confs, cls_ids):
all_boxes.append([float(x1), float(y1), float(x2), float(y2), float(c), int(cls_id)])
# 2. Sliced Grid Pass
if img_w > slice_size or img_h > slice_size:
step_x = int(slice_size * (1 - overlap))
step_y = int(slice_size * (1 - overlap))
x_offsets = list(range(0, max(1, img_w - slice_size + step_x), step_x))
y_offsets = list(range(0, max(1, img_h - slice_size + step_y), step_y))
if x_offsets[-1] + slice_size < img_w:
x_offsets.append(img_w - slice_size)
if y_offsets[-1] + slice_size < img_h:
y_offsets.append(img_h - slice_size)
for y0 in y_offsets:
for x0 in x_offsets:
x1_crop = min(x0 + slice_size, img_w)
y1_crop = min(y0 + slice_size, img_h)
patch = np_img[y0:y1_crop, x0:x1_crop]
if patch.shape[0] < 100 or patch.shape[1] < 100:
continue
res_patch = model.predict(patch, conf=conf_threshold, verbose=False)
if res_patch and len(res_patch) > 0 and res_patch[0].boxes is not None and len(res_patch[0].boxes) > 0:
p_boxes = res_patch[0].boxes.xyxy.cpu().numpy()
p_confs = res_patch[0].boxes.conf.cpu().numpy()
p_cls = res_patch[0].boxes.cls.cpu().numpy().astype(int)
for (px1, py1, px2, py2), c, cls_id in zip(p_boxes, p_confs, p_cls):
gx1 = x0 + px1
gy1 = y0 + py1
gx2 = x0 + px2
gy2 = y0 + py2
all_boxes.append([float(gx1), float(gy1), float(gx2), float(gy2), float(c), int(cls_id)])
final_boxes = apply_nms(all_boxes, iou_threshold=iou_threshold)
return final_boxes, img_w, img_h
if __name__ == "__main__":
images = sorted(list(Path("data/images").glob("*.jpg")))[:50]
print(f"Testing Sliced Inference on {len(images)} images...")
model = YOLOWorld("yolov8s-worldv2.pt")
model.set_classes(CLASS_PROMPTS)
counts = {name: 0 for name in CLASS_NAMES}
total_boxes = 0
for img_p in images:
boxes, w, h = predict_sliced(model, img_p, conf_threshold=0.02)
for b in boxes:
cls_name = CLASS_NAMES[b[5]]
counts[cls_name] += 1
total_boxes += 1
print("Sample Results across 50 images:")
print("Total boxes:", total_boxes)
for k, v in counts.items():
print(f" {k:25s}: {v}")