- engine/defect_classes: HRIPCB 6类缺陷定义 + 4类扩展 + severity排序 - engine/base: DefectBox / DetectResult 数据类 + BaseInferenceEngine 抽象基类 - engine/ultralytics_adapter: YOLOv8 .pt 推理适配器 + warmup - engine/annotator: 按 severity 着色的标注图生成 + base64 编码 - engine/loader: 单例管理 + asyncio.Lock 推理串行化 + 热重载支持 - config: Pydantic v1 BaseSettings,读取 .env - schema: DetectResponse / HealthResponse / ReloadRequest 等响应模型 - api/detect: POST /api/detect,内存读图,推理锁保护 - api/health: GET /api/health - api/model: POST /api/model/reload 热重载接口 - main: FastAPI lifespan 启动加载模型 测试通过:/api/health 200,/api/detect 空图返回 pass,标注图 base64 正常 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
import base64
|
|
from typing import Tuple
|
|
|
|
import cv2
|
|
import numpy as np
|
|
|
|
from .base import DetectResult
|
|
|
|
# 按严重程度着色,BGR格式
|
|
SEVERITY_COLORS: dict = {
|
|
"fatal": (0, 0, 220),
|
|
"major": (0, 128, 255),
|
|
"minor": (0, 215, 255),
|
|
"rework": (255, 165, 0),
|
|
"none": (180, 180, 180),
|
|
}
|
|
|
|
|
|
def annotate(image: np.ndarray, result: DetectResult) -> np.ndarray:
|
|
img = image.copy()
|
|
for d in result.defects:
|
|
color: Tuple = SEVERITY_COLORS.get(d.severity, (180, 180, 180))
|
|
x1, y1, x2, y2 = [int(v) for v in d.box_xyxy]
|
|
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
|
|
label = f"{d.class_name_zh} {d.confidence:.2f}"
|
|
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
|
|
cv2.rectangle(img, (x1, y1 - th - 6), (x1 + tw + 4, y1), color, -1)
|
|
cv2.putText(img, label, (x1 + 2, y1 - 4),
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
|
|
return img
|
|
|
|
|
|
def to_base64(image: np.ndarray, quality: int = 85) -> str:
|
|
ok, buf = cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
|
if not ok:
|
|
raise RuntimeError("图像编码失败")
|
|
return base64.b64encode(buf.tobytes()).decode()
|