CalibrationEngine.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using AutoFocusTool.Serial;
  6. using AutoFocusTool.Imaging;
  7. using SerialCamera = AutoFocusTool.Camera.Camera;
  8. namespace AutoFocusTool.Calib
  9. {
  10. /// <summary>
  11. /// 自动标定引擎(可复用,GUI/命令行共用)。封装单well标定四步:
  12. /// ①粗对焦(中央40% ROI) → ②水平扫描找最居中位置 → ③曝光二分(well内ROI) → ④精对焦(0.95r ROI + 平滑插值)
  13. /// 通过回调上报进度(文字)与实时帧(byte[]),便于界面实时显示。
  14. /// </summary>
  15. public class CalibrationEngine
  16. {
  17. readonly int W, H; // 取自相机实际分辨率,绝不能硬编码
  18. readonly HouseMotor _motor;
  19. readonly SerialCamera _cam;
  20. public Action<string> Log;
  21. public Action<byte[]> OnFrame; // 实时帧回调(原始BGR)
  22. public Action<string, WellCircle, ExposureInfo> OnStep; // 步骤+当前圆/曝光
  23. /// <summary>居中容差(Y偏移百分比),落入即合格,避免来回震荡。</summary>
  24. public double CenterTolPct = 12;
  25. /// <summary>粗扫范围(脉冲,零点±range)与步数。</summary>
  26. public int HScanRange = 4000;
  27. public int HScanSteps = 7;
  28. /// <summary>细扫步数(在粗扫最佳点附近精调Y)。</summary>
  29. public int FineScanSteps = 7;
  30. /// <summary>Z扫描半幅与层数。</summary>
  31. public int ZHalf = 1500, ZLayers = 9;
  32. public int ExpLo = 10, ExpHi = 800;
  33. /// <summary>扫描时电机稳定延时(ms)。小步移动无需1500ms,用短延时大幅提速。</summary>
  34. public int ScanDelayMs = 350;
  35. /// <summary>粗对焦层数(先让well清晰,再居中)。</summary>
  36. public int CoarseFocusLayers = 7;
  37. /// <summary>居中扫描用的固定曝光(well是暗背景上中灰盘,HScan实测~60可清晰检圆)。</summary>
  38. public Action<byte[], string> DebugSave; // 诊断存图(帧,文件名前缀),可选
  39. public int CenterScanExposure = 60;
  40. // ── 行程限位(所有电机移动前钳到该区间)──
  41. /// <summary>水平电机行程下/上限脉冲(实测16个well EEPROM位置达205800,留余量到220000)。</summary>
  42. public int HMin = 0, HMax = 220000;
  43. /// <summary>垂直电机行程下/上限脉冲(旧工程软上限 125000)。</summary>
  44. public int ZMin = 0, ZMaxPulse = 125000;
  45. // ── 水平居中微调(以各well的EEPROM位置为中心做小范围Y居中)──
  46. // 实测well间距~9000、EEPROM位置已准(移到位即|偏移|<5%),故半幅须远小于间距一半(4500),
  47. // 只在小范围微调Y居中,绝不大范围扫描(否则会扫到相邻well)。
  48. /// <summary>水平微调半幅(脉冲,EEPROM位置±range)。</summary>
  49. public int HFineRange = 2000;
  50. /// <summary>水平微调步数(±2000内9步→步距500)。</summary>
  51. public int HFineSteps = 9;
  52. // ── Z 全范围粗对焦(固定中心大窗口)──
  53. /// <summary>Z 粗对焦固定中心(实测焦面集中区间 60000~120000 的中点)。</summary>
  54. public int ZCoarseCenter = 90000;
  55. /// <summary>Z 粗对焦半幅 → 区间 60000~120000。</summary>
  56. public int ZCoarseHalf = 30000;
  57. /// <summary>Z 粗对焦步距 → 约 31 层。</summary>
  58. public int ZCoarseStep = 2000;
  59. // ── Z 精对焦(围绕粗峰)──
  60. /// <summary>精对焦半幅(覆盖粗扫 ±2000 峰定位误差并留余量)。</summary>
  61. public int FineZHalf = 6000;
  62. /// <summary>精对焦步距 → 约 24 层(精度优先)。</summary>
  63. public int FineZStep = 500;
  64. public CalibrationEngine(HouseMotor motor, SerialCamera cam)
  65. {
  66. _motor = motor; _cam = cam;
  67. W = cam.Width; H = cam.Height;
  68. }
  69. /// <summary>水平脉冲钳到 [HMin,HMax],越界写 Log。</summary>
  70. int ClampH(int p)
  71. {
  72. int c = Math.Max(HMin, Math.Min(HMax, p));
  73. if (c != p) Log?.Invoke($" ⚠ 水平脉冲 {p} 越界,钳到 {c} [{HMin},{HMax}]");
  74. return c;
  75. }
  76. /// <summary>垂直脉冲钳到 [ZMin,ZMaxPulse],越界写 Log。</summary>
  77. int ClampZ(int p)
  78. {
  79. int c = Math.Max(ZMin, Math.Min(ZMaxPulse, p));
  80. if (c != p) Log?.Invoke($" ⚠ 垂直脉冲 {p} 越界,钳到 {c} [{ZMin},{ZMaxPulse}]");
  81. return c;
  82. }
  83. /// <summary>中央40% ROI(精对焦/粗对焦圆未检出时的降级,避免背景边缘带偏)。</summary>
  84. System.Drawing.Rectangle CenterRoi40()
  85. {
  86. int roiW = (int)(W * 0.4), roiH = (int)(H * 0.4);
  87. return new System.Drawing.Rectangle((W - roiW) / 2, (H - roiH) / 2, roiW, roiH);
  88. }
  89. /// <summary>
  90. /// P0-6: 关键定位移动带重试。下位机偶发不回复(串口噪声/忙)时直接放弃整个well过于脆弱,
  91. /// 重试最多 maxRetry 次,每次间隔后再试。
  92. /// </summary>
  93. bool RetryMove(Func<bool> move, string what, int maxRetry = 3)
  94. {
  95. for (int i = 0; i < maxRetry; i++)
  96. {
  97. if (move()) return true;
  98. Log?.Invoke($" {what} 移动失败,重试 {i + 1}/{maxRetry}");
  99. Thread.Sleep(400);
  100. }
  101. return false;
  102. }
  103. byte[] Grab()
  104. {
  105. int retry = 0;
  106. while (retry < 3)
  107. {
  108. try
  109. {
  110. _cam.GrabRgb();
  111. var b = _cam.GetSourceBuffer();
  112. if (b != null && b.Length > 0)
  113. {
  114. OnFrame?.Invoke(b);
  115. return b;
  116. }
  117. }
  118. catch (Exception ex)
  119. {
  120. Log?.Invoke($"抓帧失败(重试{retry + 1}/3): {ex.Message}");
  121. }
  122. retry++;
  123. Thread.Sleep(50);
  124. }
  125. throw new Exception("抓帧失败,已重试3次");
  126. }
  127. /// <summary>
  128. /// 绕 center±range 扫 steps 个水平位置,找 well 检出且 |Y偏移| 最小的位置。
  129. /// 转动培养皿让 well 在画面上下(Y)移动,故按 Y 偏移评分;优先完整。
  130. /// </summary>
  131. (int bestHPos, WellCircle bestCircle) ScanForCenter(int well, int center, int range, int steps, int delayMs = -1)
  132. {
  133. int bestHPos = center; double bestScore = double.MaxValue; WellCircle best = null;
  134. int step = steps > 1 ? 2 * range / (steps - 1) : 1;
  135. int actualDelay = delayMs > 0 ? delayMs : ScanDelayMs; // 使用传入延时或默认值
  136. // 固定中低曝光设一次即可:well 是暗背景上的中灰盘,不能按全图均值自动曝光(会过曝well盘)
  137. _cam.SetExposure(CenterScanExposure);
  138. for (int i = 0; i < steps; i++)
  139. {
  140. int hp = ClampH(center - range + step * i);
  141. _motor.HorizontalMoveTo(hp, actualDelay);
  142. var b = Grab();
  143. var c = WellDetector.Detect(b, W, H);
  144. DebugSave?.Invoke(b, $"center_w{well}_hp{hp}");
  145. Log?.Invoke(c.Found
  146. ? $" 水平{hp}: Y偏移={c.OffsetYPct:F1}% X={c.OffsetXPct:F1}% 完整={c.Complete}"
  147. : $" 水平{hp}: 未检出圆");
  148. OnStep?.Invoke($"居中扫描 hp={hp}", c, null);
  149. if (c.Found)
  150. {
  151. // 按 |Y偏移| 评分,不完整重罚
  152. double score = Math.Abs(c.OffsetYPct) + (c.Complete ? 0 : 100);
  153. if (score < bestScore) { bestScore = score; bestHPos = hp; best = c; }
  154. }
  155. }
  156. return (bestHPos, best);
  157. }
  158. /// <summary>
  159. /// 标定单个 well。eepromHPos=该well的EEPROM水平位置(扫描中心),eepromZ=Z焦准零点。
  160. /// 返回标定结果。
  161. /// </summary>
  162. public WellCalib CalibrateWell(int well, int eepromHPos, int eepromZ)
  163. {
  164. var r = new WellCalib { Well = well };
  165. // 先到 EEPROM 水平位置 + 中低曝光
  166. if (!RetryMove(() => _motor.HorizontalMoveTo(ClampH(eepromHPos), ScanDelayMs), $"well{well}初始水平"))
  167. {
  168. Log?.Invoke($"[well{well}] ✗ 电机移动到初始位置失败(已重试),跳过该well");
  169. return new WellCalib { Well = well, Note = "电机移动失败" };
  170. }
  171. _cam.SetExposure(CenterScanExposure);
  172. // ── ① 粗对焦:先让 well 清晰,否则画面模糊根本找不到圆(采纳用户洞察:
  173. // 对焦与居中耦合,焦不对→画面糊→检不出圆→无法居中。故先粗对焦)──
  174. Log?.Invoke($"[well{well}] ①粗对焦(让well清晰可检)...");
  175. int coarseZ = CoarseFocus(well);
  176. _motor.VerticalMoveTo(ClampZ(coarseZ), ScanDelayMs);
  177. Log?.Invoke($"[well{well}] → 粗对焦Z={coarseZ}");
  178. // ── ② 旋转居中(此时画面清晰,圆可稳定检出;只优化Y偏移)──
  179. // 转动培养皿让well在画面里上下(Y)移动;X的~5%固定偏移是相机/转盘硬件偏移,旋转修不了。
  180. // 实测EEPROM位置已准(移到位即|偏移|<5%),故以eepromHPos为中心做小范围微调(半幅<well间距一半),
  181. // 绝不大范围扫描(否则会扫到相邻well)。
  182. Log?.Invoke($"[well{well}] ②以EEPROM位置({eepromHPos})为中心微调Y居中...");
  183. var located = ScanForCenter(well, ClampH(eepromHPos), HFineRange, HFineSteps, 800);
  184. int bestHPos = located.bestCircle != null ? located.bestHPos : eepromHPos;
  185. WellCircle bestCircle = located.bestCircle;
  186. r.HorizontalPulse = bestHPos;
  187. r.CircleFound = bestCircle != null;
  188. r.CenterOffsetPct = bestCircle?.OffsetYPct ?? 0;
  189. if (!RetryMove(() => _motor.HorizontalMoveTo(ClampH(bestHPos), ScanDelayMs), $"well{well}居中水平"))
  190. {
  191. Log?.Invoke($"[well{well}] ✗ 电机移动到居中位置失败(已重试),跳过该well");
  192. return new WellCalib { Well = well, Note = "居中后电机移动失败" };
  193. }
  194. bool centered = bestCircle != null && Math.Abs(r.CenterOffsetPct) < CenterTolPct && bestCircle.Complete;
  195. Log?.Invoke($"[well{well}] → 居中水平={bestHPos} 残留Y偏移={r.CenterOffsetPct:F1}% " +
  196. $"(X={bestCircle?.OffsetXPct ?? 0:F1}%硬件偏移) {(centered ? "✓合格" : "(尽力而为)")}");
  197. // ── ③ 曝光二分 (well内ROI) ──
  198. Log?.Invoke($"[well{well}] ③曝光二分...");
  199. int exp = ExposureMeter.BinarySearch(ExpLo, ExpHi, e =>
  200. {
  201. _cam.SetExposure(e);
  202. // 修复: 等待足够时间让新曝光生效,并丢弃旧帧
  203. Thread.Sleep(Math.Max(200, e / 5)); // 至少2×曝光时间(单位100µs)
  204. Grab(); // 丢弃第一帧(可能是旧曝光)
  205. var b = Grab(); // 使用第二帧
  206. var c = WellDetector.Detect(b, W, H);
  207. var info = ExposureMeter.Measure(b, W, H, c);
  208. OnStep?.Invoke($"曝光二分 e={e}", c, info);
  209. return info;
  210. }, m => Log?.Invoke(m));
  211. r.Exposure = exp;
  212. _cam.SetExposure(exp);
  213. Log?.Invoke($"[well{well}] → 曝光={exp}");
  214. // ── ④ 精对焦 (well圆内ROI, 围绕粗对焦Z小范围密扫) ──
  215. Log?.Invoke($"[well{well}] ④精对焦...");
  216. // 修复P0-5: 丢弃旧帧,确保获取稳定画面
  217. Grab(); // 丢弃第一帧
  218. var b0 = Grab(); // 使用第二帧
  219. var circle = WellDetector.Detect(b0, W, H);
  220. // P1-1: 统一对焦ROI策略 - 使用0.95r保留边缘特征,避免精对焦峰值过弱
  221. // P0-4: 圆未检出时降级到中央40% ROI(与粗对焦一致),绝不用全图(背景/反光严重干扰对焦)
  222. System.Drawing.Rectangle roi = circle.Found
  223. ? new System.Drawing.Rectangle(
  224. Math.Max(0, (int)(circle.Cx - circle.Radius * 0.95)),
  225. Math.Max(0, (int)(circle.Cy - circle.Radius * 0.95)),
  226. (int)(circle.Radius * 1.9), (int)(circle.Radius * 1.9))
  227. : CenterRoi40();
  228. if (!circle.Found)
  229. Log?.Invoke($"[well{well}] ⚠ 精对焦未检出well圆,对焦ROI降级为中央40%(非全图)");
  230. int zstep = FineZStep > 0 ? FineZStep : 500;
  231. int fineLayers = 2 * FineZHalf / zstep + 1; // 半幅6000步距500 → 25层
  232. var curve = new List<(int z, double s)>();
  233. for (int i = 0; i < fineLayers; i++)
  234. {
  235. int z = coarseZ - FineZHalf + zstep * i;
  236. _motor.VerticalMoveTo(ClampZ(z), ScanDelayMs);
  237. // P0-5: 每次移动后丢弃旧帧
  238. Grab(); // 丢弃第一帧
  239. var b = Grab(); // 使用第二帧
  240. double sc = Sharpness.Compute(b, W, H, roi);
  241. curve.Add((z, sc));
  242. OnStep?.Invoke($"精对焦 {i + 1}/{fineLayers} Z={z} 分={sc:F4}", circle, null);
  243. }
  244. // P1-3: 峰值平滑与插值 - 提升对焦精度
  245. // 3点滑动平均平滑
  246. var smoothed = new List<double>();
  247. for (int i = 0; i < curve.Count; i++)
  248. {
  249. double sum = curve[i].s;
  250. int cnt = 1;
  251. if (i > 0) { sum += curve[i - 1].s; cnt++; }
  252. if (i < curve.Count - 1) { sum += curve[i + 1].s; cnt++; }
  253. smoothed.Add(sum / cnt);
  254. }
  255. // 找平滑后的峰值
  256. double max = smoothed.Max();
  257. int pk = smoothed.IndexOf(max);
  258. double mean = smoothed.Average();
  259. // 抛物线插值峰顶(如果峰值不在边界)
  260. int focusZ = curve[pk].z;
  261. if (pk > 0 && pk < curve.Count - 1)
  262. {
  263. double y0 = smoothed[pk - 1], y1 = smoothed[pk], y2 = smoothed[pk + 1];
  264. double denominator = y0 - 2 * y1 + y2;
  265. if (Math.Abs(denominator) > 1e-9)
  266. {
  267. double delta = 0.5 * (y0 - y2) / denominator; // 抛物线顶点偏移
  268. focusZ = curve[pk].z + (int)(delta * zstep);
  269. }
  270. }
  271. r.FocusZ = focusZ;
  272. r.PeakSharp = max;
  273. r.PeakRatio = mean > 1e-9 ? max / mean : 1;
  274. // 检查对焦质量:峰过弱可能是空well或对焦失败
  275. if (r.PeakRatio < 1.2)
  276. {
  277. Log?.Invoke($"[well{well}] ⚠ 对焦峰过弱(ratio={r.PeakRatio:F2}),可能空well或对焦失败");
  278. r.Note += "对焦峰弱;";
  279. }
  280. _motor.VerticalMoveTo(ClampZ(r.FocusZ), ScanDelayMs);
  281. Log?.Invoke($"[well{well}] → 最清晰Z={r.FocusZ} 峰值={max:F4} max/mean={r.PeakRatio:F2} " +
  282. $"{(r.PeakRatio < 1.2 ? "(弱峰/可能空well)" : "✓有焦点")}");
  283. r.Note = $"{(r.CircleFound ? "" : "未检到well圆;")}{(r.PeakRatio < 1.2 ? "对焦峰弱;" : "")}";
  284. return r;
  285. }
  286. /// <summary>
  287. /// 粗对焦:固定中心 ZCoarseCenter±ZCoarseHalf 按 ZCoarseStep 扫描,中央40% ROI 找焦点。
  288. /// 实测所有 well 焦面集中在 60000~120000,故用固定大窗口,不依赖 EEPROM 零点。
  289. ///
  290. /// 【已知偶发问题 2026-06-16,待复现】偶发某个 well 粗对焦选中 ~74000 的伪峰(真实焦面应在 ~86000-92000),
  291. /// 导致精对焦被锁在 74000±FineZHalf 的小窗口、最终对焦模糊,该 well 输出弱峰(max/mean≈1.0)。
  292. /// 现象特征:
  293. /// · 同一批标定里只有 1 个 well 坏,坏值固定在 ~74000,但坏的 well 编号在不同批次间变化
  294. /// (曾出现 well1 坏、well8 坏,非固定孔位、非“第一个标定的 well”)。
  295. /// · 人眼在对焦过程能看到清晰画面,但最终选出的不是它。
  296. /// 已排除的假设(真机 WellSpacing zcurve/zcurvefar 多次实测均无法复现):
  297. /// · 串口大行程移动未到位(残留位+短延时复现 → 峰仍正确 92000)
  298. /// · 相机/光源冷启动预热(冷启动立即扫 → 峰仍正确 92000)
  299. /// · 清晰度算法(已修 ÷mean,其余 15 well 全部正确)
  300. /// · “第一个 well”时序(数据证明 well1 常常正常,坏的在序列中间)
  301. /// 当前最可疑但未坐实:偶发时序导致某层电机未真正到位/画面在运动中被采样,在 74000 形成伪高频峰;
  302. /// 或该次该孔在 74000 处恰有杂质/反光的真实但“错误”的清晰特征。
  303. /// 复现率低,本轮多次测试未触发,留待下次现场捕获(建议届时开 DebugSave 存粗对焦每层图比对)。
  304. /// </summary>
  305. int CoarseFocus(int well)
  306. {
  307. int lo = ZCoarseCenter - ZCoarseHalf;
  308. int hi = ZCoarseCenter + ZCoarseHalf;
  309. int bestZ = ZCoarseCenter; double bestS = -1;
  310. // P0-6: 粗对焦使用中央40%区域ROI,避免背景干扰
  311. var centerROI = CenterRoi40();
  312. int layers = 0;
  313. for (int z = lo; z <= hi; z += ZCoarseStep)
  314. {
  315. layers++;
  316. _motor.VerticalMoveTo(ClampZ(z), ScanDelayMs);
  317. // P0-5: 丢弃旧帧
  318. Grab();
  319. var b = Grab();
  320. double sc = Sharpness.Compute(b, W, H, centerROI); // 中央ROI(避免背景带偏)
  321. if (sc > bestS) { bestS = sc; bestZ = z; }
  322. // 诊断:粗对焦逐层分数落盘(排查偶发伪峰,如74000打败真焦面90000)。格式同精对焦。
  323. Log?.Invoke($" 粗对焦 {layers} Z={z} 分={sc:F4}");
  324. OnStep?.Invoke($"粗对焦 Z={z} (区间{lo}~{hi})", null, null);
  325. }
  326. Log?.Invoke($"[well{well}] 粗对焦扫{layers}层 区间[{lo},{hi}] 步距{ZCoarseStep}");
  327. // P1: 峰落在扫描区间边界 → 真实焦面很可能在窗口之外,警示(focusZ会偏,需调整ZCoarseCenter/Half)。
  328. if (bestZ <= lo || bestZ >= hi)
  329. Log?.Invoke($"[well{well}] ⚠ 粗对焦峰落在区间边界(z={bestZ}, 区间[{lo},{hi}])," +
  330. $"真实焦面可能在窗口外,建议调整 ZCoarseCenter/ZCoarseHalf");
  331. return bestZ;
  332. }
  333. }
  334. }