therealestcoder commited on
Commit
12929f6
·
verified ·
1 Parent(s): f3a567f

Use checkpoint img_size at inference; remove backslash duplicates

Browse files

Inference now reads backbone/img_size from the checkpoint (efficientnet_b0 @ 224) instead of the stale config (384).

Files changed (11) hide show
  1. app.py +11 -10
  2. src/config.py +3 -3
  3. src/infer.py +23 -8
  4. src//__init__.py +0 -0
  5. src//api.py +0 -146
  6. src//config.py +0 -39
  7. src//dataset.py +0 -96
  8. src//infer.py +0 -175
  9. src//model.py +0 -56
  10. src//prepare_data.py +0 -135
  11. src//train.py +0 -106
app.py CHANGED
@@ -16,15 +16,10 @@ ROOT = Path(__file__).resolve().parent
16
  if str(ROOT) not in sys.path:
17
  sys.path.insert(0, str(ROOT))
18
 
19
- # inline constants so the app works even if src imports have issues
20
  DEFECT_THRESHOLD = float(os.getenv("PDD_DEFECT_THRESHOLD", 0.55))
21
- PANEL_DEFECT_RATIO = 0.005
22
- IMG_SIZE = 384
23
- PATCH_SIZE = 512
24
- PATCH_STRIDE = 256
25
- BACKBONE = os.getenv("PDD_BACKBONE", "tf_efficientnetv2_s.in21k_ft_in1k")
26
 
27
- from src.infer import load_model, predict_image, render_visualization
28
 
29
  # ── model (lazy) ───────────────────────────────────────────────────────────
30
  _device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -45,6 +40,11 @@ def _get_model():
45
  return _model
46
 
47
 
 
 
 
 
 
48
  # ── inference ──────────────────────────────────────────────────────────────
49
 
50
  def run_inference(image: np.ndarray, vin: str, threshold: float) -> tuple:
@@ -72,7 +72,8 @@ def run_inference(image: np.ndarray, vin: str, threshold: float) -> tuple:
72
  f"**Defect ratio:** {result['defect_ratio']*100:.2f}%\n\n"
73
  f"**Max patch probability:** {result['max_prob']:.3f}\n\n"
74
  f"**Defect regions found:** {len(result['boxes'])}\n\n"
75
- f"**Panel size:** {result['panel_size']['w']} × {result['panel_size']['h']} px"
 
76
  )
77
 
78
  # ── boxes table ───────────────────────────────────────────────────────
@@ -99,8 +100,8 @@ DESCRIPTION = """
99
  # 🚗 Paint Defect Detector
100
 
101
  Upload a photo of a car body panel to detect paint defects using a sliding-window
102
- **EfficientNetV2-S** classifier. The model returns a heatmap overlay with bounding
103
- boxes around defective regions.
104
 
105
  > **Note:** A trained checkpoint (`checkpoints/best.pt`) must be present.
106
  """
 
16
  if str(ROOT) not in sys.path:
17
  sys.path.insert(0, str(ROOT))
18
 
19
+ # default for the threshold slider; backbone and input size come from the checkpoint
20
  DEFECT_THRESHOLD = float(os.getenv("PDD_DEFECT_THRESHOLD", 0.55))
 
 
 
 
 
21
 
22
+ from src.infer import load_model, model_img_size, predict_image, render_visualization
23
 
24
  # ── model (lazy) ───────────────────────────────────────────────────────────
25
  _device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
40
  return _model
41
 
42
 
43
+ def _model_label(model) -> str:
44
+ """Backbone and input size as stored in the checkpoint."""
45
+ return f"{getattr(model, 'backbone_name', '?')} @ {model_img_size(model)} px"
46
+
47
+
48
  # ── inference ──────────────────────────────────────────────────────────────
49
 
50
  def run_inference(image: np.ndarray, vin: str, threshold: float) -> tuple:
 
72
  f"**Defect ratio:** {result['defect_ratio']*100:.2f}%\n\n"
73
  f"**Max patch probability:** {result['max_prob']:.3f}\n\n"
74
  f"**Defect regions found:** {len(result['boxes'])}\n\n"
75
+ f"**Panel size:** {result['panel_size']['w']} × {result['panel_size']['h']} px\n\n"
76
+ f"**Model:** {_model_label(model)}"
77
  )
78
 
79
  # ── boxes table ───────────────────────────────────────────────────────
 
100
  # 🚗 Paint Defect Detector
101
 
102
  Upload a photo of a car body panel to detect paint defects using a sliding-window
103
+ **EfficientNet** patch classifier. The model returns a heatmap overlay with bounding
104
+ boxes around defective regions. The exact model and input size are shown with each result.
105
 
106
  > **Note:** A trained checkpoint (`checkpoints/best.pt`) must be present.
107
  """
src/config.py CHANGED
@@ -14,15 +14,15 @@ SRC_DEFECT = SOURCE_DATASET / "Фото с дефектами"
14
  SRC_CLEAN = SOURCE_DATASET / "Фото без дефектов"
15
 
16
  # Архитектура
17
- BACKBONE = os.getenv("PDD_BACKBONE", "tf_efficientnetv2_s.in21k_ft_in1k") # сильный backbone из timm
18
  NUM_CLASSES = 2 # defect / clean
19
- IMG_SIZE = 384 # размер патча на входе модели
20
  PATCH_SIZE = 512 # размер вырезаемого патча из 4000x1846
21
  PATCH_STRIDE = 256 # шаг при инференсе (50% overlap)
22
  PANEL_CROP = True # автоматически вырезать панель из фона
23
 
24
  # Тренировка
25
- BATCH_SIZE = int(os.getenv("PDD_BATCH_SIZE", 16))
26
  EPOCHS = int(os.getenv("PDD_EPOCHS", 40))
27
  LR = float(os.getenv("PDD_LR", 3e-4))
28
  WEIGHT_DECAY = 1e-4
 
14
  SRC_CLEAN = SOURCE_DATASET / "Фото без дефектов"
15
 
16
  # Архитектура
17
+ BACKBONE = os.getenv("PDD_BACKBONE", "efficientnet_b0") # fast CPU-friendly backbone
18
  NUM_CLASSES = 2 # defect / clean
19
+ IMG_SIZE = int(os.getenv("PDD_IMG_SIZE", 224)) # smaller = faster on CPU
20
  PATCH_SIZE = 512 # размер вырезаемого патча из 4000x1846
21
  PATCH_STRIDE = 256 # шаг при инференсе (50% overlap)
22
  PANEL_CROP = True # автоматически вырезать панель из фона
23
 
24
  # Тренировка
25
+ BATCH_SIZE = int(os.getenv("PDD_BATCH_SIZE", 8))
26
  EPOCHS = int(os.getenv("PDD_EPOCHS", 40))
27
  LR = float(os.getenv("PDD_LR", 3e-4))
28
  WEIGHT_DECAY = 1e-4
src/infer.py CHANGED
@@ -14,6 +14,7 @@
14
  from __future__ import annotations
15
  import argparse
16
  import json
 
17
  from pathlib import Path
18
  from typing import Any
19
 
@@ -28,11 +29,19 @@ 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"):
@@ -43,6 +52,10 @@ def load_model(checkpoint: Path | str = None, device: torch.device | str = "cpu"
43
  model = DefectClassifier(backbone=backbone, pretrained=False).to(device)
44
  model.load_state_dict(state["model"])
45
  model.eval()
 
 
 
 
46
  return model
47
 
48
 
@@ -56,8 +69,9 @@ def _slide_coords(h: int, w: int, size: int, stride: int) -> list[tuple[int, int
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
 
@@ -76,10 +90,11 @@ def predict_image(image_bgr: np.ndarray, model, device,
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())
 
14
  from __future__ import annotations
15
  import argparse
16
  import json
17
+ from functools import lru_cache
18
  from pathlib import Path
19
  from typing import Any
20
 
 
29
  from .prepare_data import crop_panel, imread_unicode, imwrite_unicode
30
 
31
 
32
+ @lru_cache(maxsize=None)
33
+ def _transform(size: int) -> A.Compose:
34
+ """Препроцессинг патча под входной размер, на котором обучалась модель."""
35
+ return A.Compose([
36
+ A.Resize(size, size),
37
+ A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
38
+ ToTensorV2(),
39
+ ])
40
+
41
+
42
+ def model_img_size(model) -> int:
43
+ """Входной размер модели: из чекпоинта (img_size), иначе из конфига."""
44
+ return int(getattr(model, "img_size", None) or C.IMG_SIZE)
45
 
46
 
47
  def load_model(checkpoint: Path | str = None, device: torch.device | str = "cpu"):
 
52
  model = DefectClassifier(backbone=backbone, pretrained=False).to(device)
53
  model.load_state_dict(state["model"])
54
  model.eval()
55
+ # Размер входа берём из чекпоинта, а не из config.py: иначе при расхождении
56
+ # конфига и обученной модели патчи подаются в чужом масштабе.
57
+ model.img_size = int(state.get("img_size") or C.IMG_SIZE)
58
+ model.backbone_name = backbone
59
  return model
60
 
61
 
 
69
  return [(y, x) for y in ys for x in xs]
70
 
71
 
72
+ def _to_batch(patches: list[np.ndarray], size: int) -> torch.Tensor:
73
+ tf = _transform(size)
74
+ tensors = [tf(image=cv2.cvtColor(p, cv2.COLOR_BGR2RGB))["image"]
75
  for p in patches]
76
  return torch.stack(tensors, dim=0)
77
 
 
90
 
91
  # инференс батчами
92
  bs = 32
93
+ size = model_img_size(model)
94
  probs = []
95
  with torch.no_grad():
96
  for i in range(0, len(patches), bs):
97
+ batch = _to_batch(patches[i:i + bs], size).to(device)
98
  logits = model(batch)
99
  p = torch.softmax(logits, dim=1)[:, 1].cpu().numpy()
100
  probs.extend(p.tolist())
src//__init__.py DELETED
File without changes
src//api.py DELETED
@@ -1,146 +0,0 @@
1
- """REST API детекции дефектов окраски кузова (по ТЗ АвтоВАЗа, таблица 3).
2
-
3
- Эндпоинты:
4
- POST /predict — приём фото детали (multipart), VIN — параметром формы;
5
- возвращает JSON с дефектами, координатами и base64-визуализацией.
6
- GET /defects/{vin} — последние результаты по VIN (in-memory история).
7
- GET /health — проверка состояния сервиса.
8
-
9
- Запуск:
10
- uvicorn src.api:app --host 0.0.0.0 --port 8080
11
- """
12
- from __future__ import annotations
13
- import base64
14
- import io
15
- import time
16
- from collections import defaultdict, deque
17
- from datetime import datetime
18
- from typing import Any
19
-
20
- import cv2
21
- import numpy as np
22
- import torch
23
- from fastapi import FastAPI, File, Form, HTTPException, UploadFile
24
- from fastapi.responses import FileResponse, JSONResponse
25
- from fastapi.staticfiles import StaticFiles
26
- from pydantic import BaseModel, Field
27
-
28
- from . import config as C
29
- from .infer import load_model, predict_image, render_visualization
30
-
31
-
32
- app = FastAPI(
33
- title="Paint Defect Detection API",
34
- version="1.0.0",
35
- description="Система автоматической детекции дефектов лакокрасочного покрытия "
36
- "(крыша, капот, багажник). Соответствует требованиям ТЗ АвтоВАЗ.",
37
- )
38
-
39
- _device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
- _model = None # ленивая загрузка
41
- _history: dict[str, deque] = defaultdict(lambda: deque(maxlen=20))
42
-
43
- _STATIC_DIR = C.ROOT / "static"
44
- if _STATIC_DIR.exists():
45
- app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static")
46
-
47
-
48
- @app.get("/", include_in_schema=False)
49
- def index():
50
- """Веб-интерфейс оператора (одностраничное приложение)."""
51
- idx = _STATIC_DIR / "index.html"
52
- if idx.exists():
53
- return FileResponse(str(idx))
54
- raise HTTPException(status_code=404, detail="UI not built")
55
-
56
-
57
- def _ensure_model():
58
- global _model
59
- if _model is None:
60
- _model = load_model(device=_device)
61
- return _model
62
-
63
-
64
- class DefectBox(BaseModel):
65
- x: int; y: int; w: int; h: int
66
- confidence: float
67
- mean_prob: float
68
-
69
-
70
- class PredictResponse(BaseModel):
71
- vin: str
72
- timestamp: str
73
- is_defect: bool
74
- defect_count: int
75
- defect_ratio: float
76
- max_prob: float
77
- boxes: list[DefectBox]
78
- panel_size: dict[str, int]
79
- visualization_base64: str = Field(description="JPEG, base64-encoded, для отображения на ТВ-панели")
80
- elapsed_ms: int
81
-
82
-
83
- @app.get("/health")
84
- def health() -> dict[str, Any]:
85
- return {
86
- "status": "ok",
87
- "device": str(_device),
88
- "model_loaded": _model is not None,
89
- "checkpoint": str(C.CHECKPOINTS / "best.pt"),
90
- }
91
-
92
-
93
- @app.post("/predict", response_model=PredictResponse)
94
- async def predict(
95
- file: UploadFile = File(..., description="Фото детали кузова"),
96
- vin: str = Form(..., description="VIN автомобиля"),
97
- part: str = Form("unknown", description="Деталь: roof|hood|trunk"),
98
- threshold: float = Form(C.DEFECT_THRESHOLD),
99
- ) -> PredictResponse:
100
- if not file.content_type or not file.content_type.startswith("image/"):
101
- raise HTTPException(status_code=400, detail="Ожидался image/*")
102
- raw = await file.read()
103
- arr = np.frombuffer(raw, dtype=np.uint8)
104
- bgr = cv2.imdecode(arr, cv2.IMREAD_COLOR)
105
- if bgr is None:
106
- raise HTTPException(status_code=400, detail="Не удалось декодировать изображение")
107
-
108
- model = _ensure_model()
109
- t0 = time.time()
110
- result = predict_image(bgr, model, _device, threshold=threshold)
111
- elapsed_ms = int((time.time() - t0) * 1000)
112
-
113
- vis = render_visualization(result)
114
- ok, buf = cv2.imencode(".jpg", vis, [cv2.IMWRITE_JPEG_QUALITY, 88])
115
- vis_b64 = base64.b64encode(buf.tobytes()).decode("ascii") if ok else ""
116
-
117
- response = PredictResponse(
118
- vin=vin,
119
- timestamp=datetime.utcnow().isoformat() + "Z",
120
- is_defect=result["is_defect"],
121
- defect_count=len(result["boxes"]),
122
- defect_ratio=result["defect_ratio"],
123
- max_prob=result["max_prob"],
124
- boxes=[DefectBox(**b) for b in result["boxes"]],
125
- panel_size=result["panel_size"],
126
- visualization_base64=vis_b64,
127
- elapsed_ms=elapsed_ms,
128
- )
129
- _history[vin].append({"part": part, "ts": response.timestamp,
130
- "is_defect": response.is_defect,
131
- "defect_count": response.defect_count})
132
- return response
133
-
134
-
135
- @app.get("/defects/{vin}")
136
- def defects_by_vin(vin: str) -> dict[str, Any]:
137
- return {"vin": vin, "results": list(_history.get(vin, []))}
138
-
139
-
140
- def main():
141
- import uvicorn
142
- uvicorn.run("src.api:app", host=C.API_HOST, port=C.API_PORT, reload=False)
143
-
144
-
145
- if __name__ == "__main__":
146
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src//config.py DELETED
@@ -1,39 +0,0 @@
1
- """Конфигурация проекта детекции дефектов окраски кузова."""
2
- import os
3
- from pathlib import Path
4
-
5
- ROOT = Path(__file__).resolve().parent.parent
6
- DATA_RAW = ROOT / "data" / "raw" # raw/defect/*.jpg, raw/clean/*.jpg
7
- DATA_PATCHES = ROOT / "data" / "patches" # patches/train|val/{defect,clean}
8
- CHECKPOINTS = ROOT / "checkpoints"
9
- RUNS = ROOT / "runs"
10
-
11
- # Источник исходного датасета (АвтоВАЗ ТЗ)
12
- SOURCE_DATASET = ROOT.parent / "3_Дефекты_окраски_кузова(детали)" / "3_Дефекты_окраски_кузова(детали)"
13
- SRC_DEFECT = SOURCE_DATASET / "Фото с дефектами"
14
- SRC_CLEAN = SOURCE_DATASET / "Фото без дефектов"
15
-
16
- # Архитектура
17
- BACKBONE = os.getenv("PDD_BACKBONE", "tf_efficientnetv2_s.in21k_ft_in1k") # сильный backbone из timm
18
- NUM_CLASSES = 2 # defect / clean
19
- IMG_SIZE = 384 # размер патча на входе модели
20
- PATCH_SIZE = 512 # размер вырезаемого патча из 4000x1846
21
- PATCH_STRIDE = 256 # шаг при инференсе (50% overlap)
22
- PANEL_CROP = True # автоматически вырезать панель из фона
23
-
24
- # Тренировка
25
- BATCH_SIZE = int(os.getenv("PDD_BATCH_SIZE", 16))
26
- EPOCHS = int(os.getenv("PDD_EPOCHS", 40))
27
- LR = float(os.getenv("PDD_LR", 3e-4))
28
- WEIGHT_DECAY = 1e-4
29
- LABEL_SMOOTH = 0.05
30
- NUM_WORKERS = 2
31
- SEED = 42
32
-
33
- # Инференс / порог принятия решения
34
- DEFECT_THRESHOLD = 0.55 # вероятность для отнесения патча к "дефект"
35
- PANEL_DEFECT_RATIO = 0.005 # доля дефектных пикселей, чтобы пометить деталь как дефектную
36
-
37
- # REST API
38
- API_HOST = "0.0.0.0"
39
- API_PORT = 8080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src//dataset.py DELETED
@@ -1,96 +0,0 @@
1
- """DataLoader'ы с агрессивной аугментацией под малый датасет."""
2
- from __future__ import annotations
3
- from pathlib import Path
4
-
5
- import cv2
6
- import numpy as np
7
- from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
8
- import albumentations as A
9
- from albumentations.pytorch import ToTensorV2
10
-
11
- from . import config as C
12
- from .prepare_data import imread_unicode
13
-
14
-
15
- CLASS_TO_IDX = {"clean": 0, "defect": 1}
16
-
17
-
18
- def build_transforms(train: bool) -> A.Compose:
19
- if train:
20
- return A.Compose([
21
- A.LongestMaxSize(max_size=C.IMG_SIZE + 32),
22
- A.PadIfNeeded(min_height=C.IMG_SIZE + 32, min_width=C.IMG_SIZE + 32,
23
- border_mode=cv2.BORDER_REFLECT_101),
24
- A.RandomCrop(height=C.IMG_SIZE, width=C.IMG_SIZE),
25
- A.HorizontalFlip(p=0.5),
26
- A.VerticalFlip(p=0.5),
27
- A.RandomRotate90(p=0.5),
28
- A.OneOf([
29
- A.RandomBrightnessContrast(brightness_limit=0.25, contrast_limit=0.25, p=1.0),
30
- A.HueSaturationValue(hue_shift_limit=8, sat_shift_limit=20, val_shift_limit=20, p=1.0),
31
- A.CLAHE(clip_limit=2.0, p=1.0),
32
- ], p=0.7),
33
- A.OneOf([
34
- A.GaussianBlur(blur_limit=(3, 5), p=1.0),
35
- A.MotionBlur(blur_limit=5, p=1.0),
36
- A.GaussNoise(var_limit=(5.0, 25.0), p=1.0),
37
- ], p=0.4),
38
- # имитируем блики/тени из реального цеха
39
- A.RandomShadow(p=0.2),
40
- A.RandomSunFlare(src_radius=80, num_flare_circles_lower=1,
41
- num_flare_circles_upper=2, p=0.15),
42
- A.CoarseDropout(max_holes=4, max_height=48, max_width=48, p=0.3),
43
- A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
44
- ToTensorV2(),
45
- ])
46
- return A.Compose([
47
- A.LongestMaxSize(max_size=C.IMG_SIZE),
48
- A.PadIfNeeded(min_height=C.IMG_SIZE, min_width=C.IMG_SIZE,
49
- border_mode=cv2.BORDER_REFLECT_101),
50
- A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
51
- ToTensorV2(),
52
- ])
53
-
54
-
55
- class PatchDataset(Dataset):
56
- """Каталог: <root>/<class>/*.jpg, метки по имени папки."""
57
-
58
- def __init__(self, root: Path, train: bool):
59
- self.samples: list[tuple[Path, int]] = []
60
- for cls, idx in CLASS_TO_IDX.items():
61
- for f in (root / cls).glob("*.jpg"):
62
- self.samples.append((f, idx))
63
- if not self.samples:
64
- raise RuntimeError(f"Нет патчей в {root}. Запустите prepare_data.py")
65
- self.transform = build_transforms(train)
66
-
67
- def __len__(self) -> int:
68
- return len(self.samples)
69
-
70
- def __getitem__(self, i: int):
71
- path, label = self.samples[i]
72
- img = imread_unicode(path)
73
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
74
- img = self.transform(image=img)["image"]
75
- return img, label
76
-
77
-
78
- def make_loaders(batch_size: int = C.BATCH_SIZE, num_workers: int = C.NUM_WORKERS):
79
- train_ds = PatchDataset(C.DATA_PATCHES / "train", train=True)
80
- val_ds = PatchDataset(C.DATA_PATCHES / "val", train=False)
81
-
82
- # балансировка классов через WeightedRandomSampler
83
- labels = np.array([lbl for _, lbl in train_ds.samples])
84
- class_counts = np.bincount(labels, minlength=2).astype(np.float32)
85
- class_weights = 1.0 / np.maximum(class_counts, 1.0)
86
- sample_weights = class_weights[labels]
87
- sampler = WeightedRandomSampler(weights=sample_weights.tolist(),
88
- num_samples=len(sample_weights),
89
- replacement=True)
90
-
91
- train_loader = DataLoader(train_ds, batch_size=batch_size, sampler=sampler,
92
- num_workers=num_workers, pin_memory=True, drop_last=False)
93
- val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False,
94
- num_workers=num_workers, pin_memory=True)
95
- print(f"train: {len(train_ds)} (классы={class_counts.tolist()}) val: {len(val_ds)}")
96
- return train_loader, val_loader
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src//infer.py DELETED
@@ -1,175 +0,0 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src//model.py DELETED
@@ -1,56 +0,0 @@
1
- """Модель детекции дефектов на основе EfficientNetV2-S из timm (transfer learning)."""
2
- from __future__ import annotations
3
-
4
- import torch
5
- import torch.nn as nn
6
- import timm
7
-
8
- from . import config as C
9
-
10
-
11
- class DefectClassifier(nn.Module):
12
- """Бинарный классификатор патч/деталь: defect vs clean.
13
-
14
- Используем предобученный backbone из timm и свою классификационную голову
15
- с дропаутом — это устойчиво на малых датасетах.
16
- """
17
-
18
- def __init__(self, backbone: str = C.BACKBONE, num_classes: int = C.NUM_CLASSES,
19
- pretrained: bool = True, drop_rate: float = 0.3):
20
- super().__init__()
21
- self.backbone = timm.create_model(
22
- backbone,
23
- pretrained=pretrained,
24
- num_classes=0, # без головы — берём фичи
25
- global_pool="avg",
26
- )
27
- feat_dim = self.backbone.num_features
28
- self.head = nn.Sequential(
29
- nn.Dropout(drop_rate),
30
- nn.Linear(feat_dim, 256),
31
- nn.GELU(),
32
- nn.Dropout(drop_rate),
33
- nn.Linear(256, num_classes),
34
- )
35
-
36
- def forward(self, x: torch.Tensor) -> torch.Tensor:
37
- feats = self.backbone(x)
38
- return self.head(feats)
39
-
40
- @torch.no_grad()
41
- def predict_proba(self, x: torch.Tensor) -> torch.Tensor:
42
- return torch.softmax(self.forward(x), dim=1)
43
-
44
- def gradcam_target_layer(self) -> nn.Module:
45
- """Слой для построения Grad-CAM (последний conv-блок backbone'а)."""
46
- # У EfficientNet-семейства это последний блок перед глобальным пулингом
47
- if hasattr(self.backbone, "conv_head"):
48
- return self.backbone.conv_head
49
- # Fallback: последний блок features
50
- if hasattr(self.backbone, "blocks"):
51
- return self.backbone.blocks[-1]
52
- raise RuntimeError("Не нашёл подходящий слой для Grad-CAM")
53
-
54
-
55
- def build_model(pretrained: bool = True) -> DefectClassifier:
56
- return DefectClassifier(pretrained=pretrained)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src//prepare_data.py DELETED
@@ -1,135 +0,0 @@
1
- """Подготовка датасета: нарезка панелей кузова на патчи и разбиение train/val.
2
-
3
- Из исходных фото 4000x1846 (плоские панели — образцы окраски) автоматически
4
- вырезается область панели (по яркости/контрасту), затем нарезаются перекрытые
5
- патчи 512x512. Дефектные образцы → класс 1, образцы без дефектов → класс 0.
6
-
7
- Запуск: python -m src.prepare_data
8
- """
9
- from __future__ import annotations
10
- import shutil
11
- import random
12
- from pathlib import Path
13
-
14
- import cv2
15
- import numpy as np
16
-
17
- from . import config as C
18
-
19
-
20
- def imread_unicode(path: Path) -> np.ndarray | None:
21
- """cv2.imread не понимает Cyrillic-пути на Windows — обходим через np.fromfile."""
22
- try:
23
- data = np.fromfile(str(path), dtype=np.uint8)
24
- if data.size == 0:
25
- return None
26
- return cv2.imdecode(data, cv2.IMREAD_COLOR)
27
- except Exception:
28
- return None
29
-
30
-
31
- def imwrite_unicode(path: Path, img: np.ndarray, params=None) -> bool:
32
- ext = path.suffix or ".jpg"
33
- ok, buf = cv2.imencode(ext, img, params or [])
34
- if not ok:
35
- return False
36
- buf.tofile(str(path))
37
- return True
38
-
39
-
40
- def crop_panel(bgr: np.ndarray) -> np.ndarray:
41
- """Вырезает прямоугольник панели из светлого фона.
42
-
43
- На исходных фото панель окраски лежит на белом столе. Бинаризуем изображение
44
- по Оцу, берём наибольший контур и вырезаем его bounding box.
45
- """
46
- gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
47
- blur = cv2.GaussianBlur(gray, (9, 9), 0)
48
- # Панель темнее белого фона -> инвертированный Оцу
49
- _, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
50
- th = cv2.morphologyEx(th, cv2.MORPH_OPEN, np.ones((15, 15), np.uint8))
51
- contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
52
- if not contours:
53
- return bgr
54
- c = max(contours, key=cv2.contourArea)
55
- x, y, w, h = cv2.boundingRect(c)
56
- # отступаем внутрь, чтобы не зацепить край/тень/наклейку
57
- pad = int(0.04 * min(w, h))
58
- x1, y1 = max(0, x + pad), max(0, y + pad)
59
- x2, y2 = min(bgr.shape[1], x + w - pad), min(bgr.shape[0], y + h - pad)
60
- if x2 - x1 < 200 or y2 - y1 < 200:
61
- return bgr
62
- return bgr[y1:y2, x1:x2]
63
-
64
-
65
- def slice_patches(panel: np.ndarray, size: int, stride: int) -> list[np.ndarray]:
66
- """Нарезает панель на квадратные патчи с заданным шагом."""
67
- h, w = panel.shape[:2]
68
- if h < size or w < size:
69
- # маленькая панель: один центральный ресайз
70
- return [cv2.resize(panel, (size, size))]
71
- patches = []
72
- ys = list(range(0, h - size + 1, stride))
73
- xs = list(range(0, w - size + 1, stride))
74
- if ys[-1] != h - size:
75
- ys.append(h - size)
76
- if xs[-1] != w - size:
77
- xs.append(w - size)
78
- for y in ys:
79
- for x in xs:
80
- patches.append(panel[y:y + size, x:x + size])
81
- return patches
82
-
83
-
84
- def main(val_ratio: float = 0.2, seed: int = C.SEED) -> None:
85
- random.seed(seed)
86
- src_pairs = [
87
- (C.SRC_DEFECT, "defect"),
88
- (C.SRC_CLEAN, "clean"),
89
- ]
90
-
91
- # пересобираем выходные каталоги
92
- if C.DATA_PATCHES.exists():
93
- shutil.rmtree(C.DATA_PATCHES)
94
- for split in ("train", "val"):
95
- for cls in ("defect", "clean"):
96
- (C.DATA_PATCHES / split / cls).mkdir(parents=True, exist_ok=True)
97
-
98
- # также продублируем оригиналы в data/raw для удобства
99
- C.DATA_RAW.mkdir(parents=True, exist_ok=True)
100
- for src_dir, cls in src_pairs:
101
- out = C.DATA_RAW / cls
102
- out.mkdir(exist_ok=True)
103
- for f in src_dir.iterdir():
104
- if f.suffix.lower() in {".jpg", ".jpeg", ".png"}:
105
- shutil.copy2(f, out / f.name)
106
-
107
- total = {"train": 0, "val": 0}
108
- for src_dir, cls in src_pairs:
109
- files = [f for f in src_dir.iterdir()
110
- if f.suffix.lower() in {".jpg", ".jpeg", ".png"}]
111
- random.shuffle(files)
112
- n_val = max(1, int(len(files) * val_ratio))
113
- val_files = set(files[:n_val])
114
-
115
- for f in files:
116
- split = "val" if f in val_files else "train"
117
- img = imread_unicode(f)
118
- if img is None:
119
- print(f"[skip] не удалось прочитать {f}")
120
- continue
121
- panel = crop_panel(img) if C.PANEL_CROP else img
122
- patches = slice_patches(panel, C.PATCH_SIZE, C.PATCH_STRIDE)
123
- stem = f.stem
124
- for i, p in enumerate(patches):
125
- out_path = C.DATA_PATCHES / split / cls / f"{stem}_{i:03d}.jpg"
126
- imwrite_unicode(out_path, p, [cv2.IMWRITE_JPEG_QUALITY, 92])
127
- total[split] += 1
128
- print(f"[{split}/{cls}] {f.name}: {len(patches)} патчей")
129
-
130
- print(f"\nИтого патчей: train={total['train']} val={total['val']}")
131
- print(f"Готовый датасет: {C.DATA_PATCHES}")
132
-
133
-
134
- if __name__ == "__main__":
135
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src//train.py DELETED
@@ -1,106 +0,0 @@
1
- """Обучение модели детекции дефектов окраски кузова.
2
-
3
- Запуск: python -m src.train
4
- """
5
- from __future__ import annotations
6
- import time
7
- import json
8
- from pathlib import Path
9
-
10
- import numpy as np
11
- import torch
12
- import torch.nn as nn
13
- from torch.optim import AdamW
14
- from torch.optim.lr_scheduler import CosineAnnealingLR
15
- from sklearn.metrics import roc_auc_score, f1_score, confusion_matrix
16
- from tqdm import tqdm
17
-
18
- from . import config as C
19
- from .dataset import make_loaders
20
- from .model import build_model
21
-
22
-
23
- def set_seed(seed: int) -> None:
24
- import random
25
- random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
26
- torch.cuda.manual_seed_all(seed)
27
-
28
-
29
- def evaluate(model: nn.Module, loader, device) -> dict:
30
- model.eval()
31
- all_p, all_y = [], []
32
- with torch.no_grad():
33
- for x, y in loader:
34
- x = x.to(device, non_blocking=True)
35
- logits = model(x)
36
- prob = torch.softmax(logits, dim=1)[:, 1]
37
- all_p.append(prob.cpu().numpy())
38
- all_y.append(y.numpy())
39
- p = np.concatenate(all_p); y = np.concatenate(all_y)
40
- pred = (p >= C.DEFECT_THRESHOLD).astype(int)
41
- metrics = {
42
- "auc": float(roc_auc_score(y, p)) if len(np.unique(y)) > 1 else float("nan"),
43
- "f1": float(f1_score(y, pred, zero_division=0)),
44
- "acc": float((pred == y).mean()),
45
- "cm": confusion_matrix(y, pred, labels=[0, 1]).tolist(),
46
- }
47
- return metrics
48
-
49
-
50
- def main() -> None:
51
- set_seed(C.SEED)
52
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
53
- print(f"Устройство: {device}")
54
-
55
- train_loader, val_loader = make_loaders()
56
- model = build_model(pretrained=True).to(device)
57
-
58
- optim = AdamW(model.parameters(), lr=C.LR, weight_decay=C.WEIGHT_DECAY)
59
- sched = CosineAnnealingLR(optim, T_max=C.EPOCHS)
60
- criterion = nn.CrossEntropyLoss(label_smoothing=C.LABEL_SMOOTH)
61
-
62
- C.CHECKPOINTS.mkdir(parents=True, exist_ok=True)
63
- C.RUNS.mkdir(parents=True, exist_ok=True)
64
- history = []
65
- best_score = -1.0
66
- best_path = C.CHECKPOINTS / "best.pt"
67
-
68
- for epoch in range(1, C.EPOCHS + 1):
69
- model.train()
70
- running = 0.0
71
- n = 0
72
- t0 = time.time()
73
- pbar = tqdm(train_loader, desc=f"Эпоха {epoch}/{C.EPOCHS}")
74
- for x, y in pbar:
75
- x = x.to(device, non_blocking=True); y = y.to(device, non_blocking=True)
76
- optim.zero_grad(set_to_none=True)
77
- logits = model(x)
78
- loss = criterion(logits, y)
79
- loss.backward()
80
- torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
81
- optim.step()
82
- running += float(loss.item()) * x.size(0); n += x.size(0)
83
- pbar.set_postfix(loss=f"{running / n:.4f}")
84
- sched.step()
85
-
86
- metrics = evaluate(model, val_loader, device)
87
- score = metrics["auc"] if not np.isnan(metrics["auc"]) else metrics["f1"]
88
- elapsed = time.time() - t0
89
- print(f" val: AUC={metrics['auc']:.3f} F1={metrics['f1']:.3f} "
90
- f"acc={metrics['acc']:.3f} cm={metrics['cm']} ({elapsed:.1f}s)")
91
- history.append({"epoch": epoch, "train_loss": running / max(n, 1), **metrics})
92
-
93
- if score > best_score:
94
- best_score = score
95
- torch.save({"model": model.state_dict(),
96
- "backbone": C.BACKBONE,
97
- "img_size": C.IMG_SIZE,
98
- "metrics": metrics}, best_path)
99
- print(f" ✓ сохранён лучший чекпоинт {best_path.name} (score={best_score:.3f})")
100
-
101
- (C.RUNS / "history.json").write_text(json.dumps(history, indent=2, ensure_ascii=False))
102
- print(f"\nГотово. Лучший score: {best_score:.3f}\nЧекпоинт: {best_path}")
103
-
104
-
105
- if __name__ == "__main__":
106
- main()