therealestcoder commited on
Commit
a496893
·
verified ·
1 Parent(s): ff1ef32

Upload src\infer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src//infer.py +175 -0
src//infer.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Инференс по полному фото детали кузова.
2
+
3
+ Алгоритм:
4
+ 1) Вырезаем панель из фона.
5
+ 2) Скользящим окном (PATCH_SIZE с шагом PATCH_STRIDE) собираем патчи.
6
+ 3) Прогоняем батчем через сеть -> вероятность "defect" для каждого патча.
7
+ 4) Аккумулируем вероятности в карту дефектов того же размера, что панель.
8
+ 5) Возвращаем: вердикт по детали, маску, координаты bounding box'ов дефектов,
9
+ визуализацию (наложение тепловой карты).
10
+
11
+ Запуск:
12
+ python -m src.infer --image путь/к/фото.jpg --out runs/result.jpg
13
+ """
14
+ from __future__ import annotations
15
+ import argparse
16
+ import json
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import torch
23
+ import albumentations as A
24
+ from albumentations.pytorch import ToTensorV2
25
+
26
+ from . import config as C
27
+ from .model import build_model
28
+ from .prepare_data import crop_panel, imread_unicode, imwrite_unicode
29
+
30
+
31
+ _TRANSFORM = A.Compose([
32
+ A.Resize(C.IMG_SIZE, C.IMG_SIZE),
33
+ A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
34
+ ToTensorV2(),
35
+ ])
36
+
37
+
38
+ def load_model(checkpoint: Path | str = None, device: torch.device | str = "cpu"):
39
+ ckpt_path = Path(checkpoint) if checkpoint else C.CHECKPOINTS / "best.pt"
40
+ state = torch.load(ckpt_path, map_location=device, weights_only=False)
41
+ from .model import DefectClassifier
42
+ backbone = state.get("backbone", C.BACKBONE)
43
+ model = DefectClassifier(backbone=backbone, pretrained=False).to(device)
44
+ model.load_state_dict(state["model"])
45
+ model.eval()
46
+ return model
47
+
48
+
49
+ def _slide_coords(h: int, w: int, size: int, stride: int) -> list[tuple[int, int]]:
50
+ if h < size or w < size:
51
+ return [(0, 0)]
52
+ ys = list(range(0, h - size + 1, stride))
53
+ xs = list(range(0, w - size + 1, stride))
54
+ if ys[-1] != h - size: ys.append(h - size)
55
+ if xs[-1] != w - size: xs.append(w - size)
56
+ return [(y, x) for y in ys for x in xs]
57
+
58
+
59
+ def _to_batch(patches: list[np.ndarray]) -> torch.Tensor:
60
+ tensors = [_TRANSFORM(image=cv2.cvtColor(p, cv2.COLOR_BGR2RGB))["image"]
61
+ for p in patches]
62
+ return torch.stack(tensors, dim=0)
63
+
64
+
65
+ def predict_image(image_bgr: np.ndarray, model, device,
66
+ threshold: float = C.DEFECT_THRESHOLD,
67
+ panel_defect_ratio: float = C.PANEL_DEFECT_RATIO) -> dict[str, Any]:
68
+ """Возвращает dict с результатом анализа полного фото."""
69
+ panel = crop_panel(image_bgr) if C.PANEL_CROP else image_bgr
70
+ H, W = panel.shape[:2]
71
+ coords = _slide_coords(H, W, C.PATCH_SIZE, C.PATCH_STRIDE)
72
+ patches = [panel[y:y + C.PATCH_SIZE, x:x + C.PATCH_SIZE] for y, x in coords]
73
+ if not patches:
74
+ patches = [cv2.resize(panel, (C.PATCH_SIZE, C.PATCH_SIZE))]
75
+ coords = [(0, 0)]
76
+
77
+ # инференс батчами
78
+ bs = 32
79
+ probs = []
80
+ with torch.no_grad():
81
+ for i in range(0, len(patches), bs):
82
+ batch = _to_batch(patches[i:i + bs]).to(device)
83
+ logits = model(batch)
84
+ p = torch.softmax(logits, dim=1)[:, 1].cpu().numpy()
85
+ probs.extend(p.tolist())
86
+
87
+ # карта вероятностей дефекта по панели
88
+ heatmap = np.zeros((H, W), dtype=np.float32)
89
+ weights = np.zeros((H, W), dtype=np.float32)
90
+ for (y, x), p in zip(coords, probs):
91
+ ye = min(y + C.PATCH_SIZE, H); xe = min(x + C.PATCH_SIZE, W)
92
+ heatmap[y:ye, x:xe] += p
93
+ weights[y:ye, x:xe] += 1.0
94
+ heatmap = heatmap / np.maximum(weights, 1e-6)
95
+
96
+ # бинарная маска дефектов
97
+ mask = (heatmap >= threshold).astype(np.uint8) * 255
98
+ defect_pixels = int(mask.sum() / 255)
99
+ defect_ratio = defect_pixels / max(H * W, 1)
100
+
101
+ # bbox'ы дефектов
102
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
103
+ boxes = []
104
+ for c in contours:
105
+ if cv2.contourArea(c) < 200: # отсекаем шум
106
+ continue
107
+ x, y, w, h = cv2.boundingRect(c)
108
+ roi = heatmap[y:y + h, x:x + w]
109
+ boxes.append({
110
+ "x": int(x), "y": int(y), "w": int(w), "h": int(h),
111
+ "confidence": float(roi.max()),
112
+ "mean_prob": float(roi.mean()),
113
+ })
114
+
115
+ is_defect = bool(defect_ratio >= panel_defect_ratio and len(boxes) > 0)
116
+
117
+ return {
118
+ "is_defect": is_defect,
119
+ "defect_ratio": float(defect_ratio),
120
+ "max_prob": float(heatmap.max()),
121
+ "boxes": boxes,
122
+ "panel_size": {"h": int(H), "w": int(W)},
123
+ "heatmap": heatmap,
124
+ "panel": panel,
125
+ }
126
+
127
+
128
+ def render_visualization(result: dict) -> np.ndarray:
129
+ """Накладывает тепловую карту и bbox'ы на панель."""
130
+ panel = result["panel"].copy()
131
+ hm = result["heatmap"]
132
+ hm_norm = np.clip(hm, 0.0, 1.0)
133
+ colored = cv2.applyColorMap((hm_norm * 255).astype(np.uint8), cv2.COLORMAP_JET)
134
+ overlay = cv2.addWeighted(panel, 0.6, colored, 0.4, 0)
135
+
136
+ for b in result["boxes"]:
137
+ x, y, w, h = b["x"], b["y"], b["w"], b["h"]
138
+ cv2.rectangle(overlay, (x, y), (x + w, y + h), (0, 0, 255), 3)
139
+ label = f"{b['confidence']:.2f}"
140
+ cv2.putText(overlay, label, (x, max(20, y - 8)),
141
+ cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
142
+
143
+ verdict = "DEFECT" if result["is_defect"] else "OK"
144
+ color = (0, 0, 255) if result["is_defect"] else (0, 200, 0)
145
+ cv2.rectangle(overlay, (0, 0), (320, 60), (0, 0, 0), -1)
146
+ cv2.putText(overlay, verdict, (12, 44), cv2.FONT_HERSHEY_SIMPLEX, 1.4, color, 3)
147
+ return overlay
148
+
149
+
150
+ def main() -> None:
151
+ ap = argparse.ArgumentParser()
152
+ ap.add_argument("--image", required=True, type=Path)
153
+ ap.add_argument("--checkpoint", type=Path, default=None)
154
+ ap.add_argument("--out", type=Path, default=C.RUNS / "result.jpg")
155
+ ap.add_argument("--threshold", type=float, default=C.DEFECT_THRESHOLD)
156
+ args = ap.parse_args()
157
+
158
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
159
+ model = load_model(args.checkpoint, device)
160
+ bgr = imread_unicode(args.image)
161
+ if bgr is None:
162
+ raise SystemExit(f"Не удалось прочитать {args.image}")
163
+ res = predict_image(bgr, model, device, threshold=args.threshold)
164
+
165
+ args.out.parent.mkdir(parents=True, exist_ok=True)
166
+ imwrite_unicode(args.out, render_visualization(res), [cv2.IMWRITE_JPEG_QUALITY, 90])
167
+
168
+ # JSON-отчёт без numpy-полей
169
+ report = {k: v for k, v in res.items() if k not in {"heatmap", "panel"}}
170
+ print(json.dumps(report, indent=2, ensure_ascii=False))
171
+ print(f"\nВизуализация: {args.out}")
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()