# grinding_defect_detect.py
# 打磨件表面缺陷在线检测 —— 推理主干（YOLOv8n）
# 配套文章：打磨工位 AI 视觉在线质检：从选型到代码的完整落地
# ⚠️ 参数声明：以下 ROI / 模型路径 / 置信度均为示例，须按你的工位、相机、线体实测标定后使用。

import cv2, numpy as np
from ultralytics import YOLO

MODEL_PATH = "models/grind_yolov8n.pt"   # 你训练的权重
ROI = (120, 80, 520, 440)                # (x,y,w,h) 打磨面 ROI，按你工位标定
CONF_THRES = 0.45

def anti_glare_preprocess(frame, roi):
    """ROI 裁剪 + CLAHE 提对比 + 高光掩膜。金属反光过曝区不参与分类置信度。"""
    x, y, w, h = roi
    crop = frame[y:y+h, x:x+w]
    lab = cv2.cvtColor(crop, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    l = clahe.apply(l)
    crop = cv2.cvtColor(cv2.merge([l,a,b]), cv2.COLOR_LAB2BGR)
    gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
    _, hl = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)  # 高光掩膜
    return crop, hl

def main():
    model = YOLO(MODEL_PATH)
    cap = cv2.VideoCapture(0)  # 替换为工业相机 SDK / GigE 流
    try:
        while True:
            ok, frame = cap.read()
            if not ok:
                break
            crop, _ = anti_glare_preprocess(frame, ROI)
            res = model.predict(crop, conf=CONF_THRES, verbose=False)[0]
            cv2.imshow("grind_qc", res.plot())
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    finally:
        cap.release()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
