CalibrationEngine.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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>水平电机行程下/上限脉冲(旧工程自检值 70000)。</summary>
  42. public int HMin = 0, HMax = 70000;
  43. /// <summary>垂直电机行程下/上限脉冲(旧工程软上限 125000)。</summary>
  44. public int ZMin = 0, ZMaxPulse = 125000;
  45. // ── 水平全行程粗扫定位 ──
  46. /// <summary>水平全行程粗扫起点/终点/步距。命中完整圆即停。</summary>
  47. public int HCoarseStart = 0;
  48. public int HCoarseEnd = 70000;
  49. public int HCoarseStep = 2000;
  50. // ── Z 全范围粗对焦(固定中心大窗口)──
  51. /// <summary>Z 粗对焦固定中心(实测焦面集中区间 60000~120000 的中点)。</summary>
  52. public int ZCoarseCenter = 90000;
  53. /// <summary>Z 粗对焦半幅 → 区间 60000~120000。</summary>
  54. public int ZCoarseHalf = 30000;
  55. /// <summary>Z 粗对焦步距 → 约 31 层。</summary>
  56. public int ZCoarseStep = 2000;
  57. // ── Z 精对焦(围绕粗峰)──
  58. /// <summary>精对焦半幅(覆盖粗扫 ±2000 峰定位误差并留余量)。</summary>
  59. public int FineZHalf = 6000;
  60. /// <summary>精对焦步距 → 约 24 层(精度优先)。</summary>
  61. public int FineZStep = 500;
  62. public CalibrationEngine(HouseMotor motor, SerialCamera cam)
  63. {
  64. _motor = motor; _cam = cam;
  65. W = cam.Width; H = cam.Height;
  66. }
  67. /// <summary>水平脉冲钳到 [HMin,HMax],越界写 Log。</summary>
  68. int ClampH(int p)
  69. {
  70. int c = Math.Max(HMin, Math.Min(HMax, p));
  71. if (c != p) Log?.Invoke($" ⚠ 水平脉冲 {p} 越界,钳到 {c} [{HMin},{HMax}]");
  72. return c;
  73. }
  74. /// <summary>垂直脉冲钳到 [ZMin,ZMaxPulse],越界写 Log。</summary>
  75. int ClampZ(int p)
  76. {
  77. int c = Math.Max(ZMin, Math.Min(ZMaxPulse, p));
  78. if (c != p) Log?.Invoke($" ⚠ 垂直脉冲 {p} 越界,钳到 {c} [{ZMin},{ZMaxPulse}]");
  79. return c;
  80. }
  81. /// <summary>中央40% ROI(精对焦/粗对焦圆未检出时的降级,避免背景边缘带偏)。</summary>
  82. System.Drawing.Rectangle CenterRoi40()
  83. {
  84. int roiW = (int)(W * 0.4), roiH = (int)(H * 0.4);
  85. return new System.Drawing.Rectangle((W - roiW) / 2, (H - roiH) / 2, roiW, roiH);
  86. }
  87. /// <summary>
  88. /// P0-6: 关键定位移动带重试。下位机偶发不回复(串口噪声/忙)时直接放弃整个well过于脆弱,
  89. /// 重试最多 maxRetry 次,每次间隔后再试。
  90. /// </summary>
  91. bool RetryMove(Func<bool> move, string what, int maxRetry = 3)
  92. {
  93. for (int i = 0; i < maxRetry; i++)
  94. {
  95. if (move()) return true;
  96. Log?.Invoke($" {what} 移动失败,重试 {i + 1}/{maxRetry}");
  97. Thread.Sleep(400);
  98. }
  99. return false;
  100. }
  101. byte[] Grab()
  102. {
  103. int retry = 0;
  104. while (retry < 3)
  105. {
  106. try
  107. {
  108. _cam.GrabRgb();
  109. var b = _cam.GetSourceBuffer();
  110. if (b != null && b.Length > 0)
  111. {
  112. OnFrame?.Invoke(b);
  113. return b;
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. Log?.Invoke($"抓帧失败(重试{retry + 1}/3): {ex.Message}");
  119. }
  120. retry++;
  121. Thread.Sleep(50);
  122. }
  123. throw new Exception("抓帧失败,已重试3次");
  124. }
  125. /// <summary>
  126. /// 绕 center±range 扫 steps 个水平位置,找 well 检出且 |Y偏移| 最小的位置。
  127. /// 转动培养皿让 well 在画面上下(Y)移动,故按 Y 偏移评分;优先完整。
  128. /// </summary>
  129. (int bestHPos, WellCircle bestCircle) ScanForCenter(int well, int center, int range, int steps, int delayMs = -1)
  130. {
  131. int bestHPos = center; double bestScore = double.MaxValue; WellCircle best = null;
  132. int step = steps > 1 ? 2 * range / (steps - 1) : 1;
  133. int actualDelay = delayMs > 0 ? delayMs : ScanDelayMs; // 使用传入延时或默认值
  134. // 固定中低曝光设一次即可:well 是暗背景上的中灰盘,不能按全图均值自动曝光(会过曝well盘)
  135. _cam.SetExposure(CenterScanExposure);
  136. for (int i = 0; i < steps; i++)
  137. {
  138. int hp = center - range + step * i;
  139. if (hp < 0) continue;
  140. _motor.HorizontalMoveTo(hp, actualDelay);
  141. var b = Grab();
  142. var c = WellDetector.Detect(b, W, H);
  143. DebugSave?.Invoke(b, $"center_w{well}_hp{hp}");
  144. Log?.Invoke(c.Found
  145. ? $" 水平{hp}: Y偏移={c.OffsetYPct:F1}% X={c.OffsetXPct:F1}% 完整={c.Complete}"
  146. : $" 水平{hp}: 未检出圆");
  147. OnStep?.Invoke($"居中扫描 hp={hp}", c, null);
  148. if (c.Found)
  149. {
  150. // 按 |Y偏移| 评分,不完整重罚
  151. double score = Math.Abs(c.OffsetYPct) + (c.Complete ? 0 : 100);
  152. if (score < bestScore) { bestScore = score; bestHPos = hp; best = c; }
  153. }
  154. }
  155. return (bestHPos, best);
  156. }
  157. /// <summary>
  158. /// 标定单个 well。eepromHPos=该well的EEPROM水平位置(扫描中心),eepromZ=Z焦准零点。
  159. /// 返回标定结果。
  160. /// </summary>
  161. public WellCalib CalibrateWell(int well, int eepromHPos, int eepromZ)
  162. {
  163. var r = new WellCalib { Well = well };
  164. // 先到 EEPROM 水平位置 + 中低曝光
  165. if (!RetryMove(() => _motor.HorizontalMoveTo(eepromHPos, ScanDelayMs), $"well{well}初始水平"))
  166. {
  167. Log?.Invoke($"[well{well}] ✗ 电机移动到初始位置失败(已重试),跳过该well");
  168. return new WellCalib { Well = well, Note = "电机移动失败" };
  169. }
  170. _cam.SetExposure(CenterScanExposure);
  171. // ── ① 粗对焦:先让 well 清晰,否则画面模糊根本找不到圆(采纳用户洞察:
  172. // 对焦与居中耦合,焦不对→画面糊→检不出圆→无法居中。故先粗对焦)──
  173. Log?.Invoke($"[well{well}] ①粗对焦(让well清晰可检)...");
  174. int coarseZ = CoarseFocus(well, eepromZ, ZHalf, CoarseFocusLayers);
  175. _motor.VerticalMoveTo(coarseZ, ScanDelayMs);
  176. Log?.Invoke($"[well{well}] → 粗对焦Z={coarseZ}");
  177. // ── ② 旋转居中(此时画面清晰,圆可稳定检出;只优化Y偏移)──
  178. // 转动培养皿让well在画面里上下(Y)移动;X的~5%固定偏移是相机/转盘硬件偏移,旋转修不了。
  179. Log?.Invoke($"[well{well}] ②旋转居中(优化Y偏移)...");
  180. var coarse = ScanForCenter(well, eepromHPos, HScanRange, HScanSteps);
  181. int fineRange = Math.Max(300, 2 * HScanRange / Math.Max(1, HScanSteps - 1));
  182. var fine = ScanForCenter(well, coarse.bestHPos, fineRange, FineScanSteps, 800); // 细扫用800ms长延时确保检测准确
  183. int bestHPos = fine.bestCircle != null ? fine.bestHPos : coarse.bestHPos;
  184. WellCircle bestCircle = fine.bestCircle ?? coarse.bestCircle;
  185. r.HorizontalPulse = bestHPos;
  186. r.CircleFound = bestCircle != null;
  187. r.CenterOffsetPct = bestCircle?.OffsetYPct ?? 0;
  188. if (!RetryMove(() => _motor.HorizontalMoveTo(bestHPos, ScanDelayMs), $"well{well}居中水平"))
  189. {
  190. Log?.Invoke($"[well{well}] ✗ 电机移动到居中位置失败(已重试),跳过该well");
  191. return new WellCalib { Well = well, Note = "居中后电机移动失败" };
  192. }
  193. bool centered = bestCircle != null && Math.Abs(r.CenterOffsetPct) < CenterTolPct && bestCircle.Complete;
  194. Log?.Invoke($"[well{well}] → 居中水平={bestHPos} 残留Y偏移={r.CenterOffsetPct:F1}% " +
  195. $"(X={bestCircle?.OffsetXPct ?? 0:F1}%硬件偏移) {(centered ? "✓合格" : "(尽力而为)")}");
  196. // ── ③ 曝光二分 (well内ROI) ──
  197. Log?.Invoke($"[well{well}] ③曝光二分...");
  198. int exp = ExposureMeter.BinarySearch(ExpLo, ExpHi, e =>
  199. {
  200. _cam.SetExposure(e);
  201. // 修复: 等待足够时间让新曝光生效,并丢弃旧帧
  202. Thread.Sleep(Math.Max(200, e / 5)); // 至少2×曝光时间(单位100µs)
  203. Grab(); // 丢弃第一帧(可能是旧曝光)
  204. var b = Grab(); // 使用第二帧
  205. var c = WellDetector.Detect(b, W, H);
  206. var info = ExposureMeter.Measure(b, W, H, c);
  207. OnStep?.Invoke($"曝光二分 e={e}", c, info);
  208. return info;
  209. }, m => Log?.Invoke(m));
  210. r.Exposure = exp;
  211. _cam.SetExposure(exp);
  212. Log?.Invoke($"[well{well}] → 曝光={exp}");
  213. // ── ④ 精对焦 (well圆内ROI, 围绕粗对焦Z小范围密扫) ──
  214. Log?.Invoke($"[well{well}] ④精对焦...");
  215. // 修复P0-5: 丢弃旧帧,确保获取稳定画面
  216. Grab(); // 丢弃第一帧
  217. var b0 = Grab(); // 使用第二帧
  218. var circle = WellDetector.Detect(b0, W, H);
  219. // P1-1: 统一对焦ROI策略 - 使用0.95r保留边缘特征,避免精对焦峰值过弱
  220. // P0-4: 圆未检出时降级到中央40% ROI(与粗对焦一致),绝不用全图(背景/反光严重干扰对焦)
  221. System.Drawing.Rectangle roi = circle.Found
  222. ? new System.Drawing.Rectangle(
  223. Math.Max(0, (int)(circle.Cx - circle.Radius * 0.95)),
  224. Math.Max(0, (int)(circle.Cy - circle.Radius * 0.95)),
  225. (int)(circle.Radius * 1.9), (int)(circle.Radius * 1.9))
  226. : CenterRoi40();
  227. if (!circle.Found)
  228. Log?.Invoke($"[well{well}] ⚠ 精对焦未检出well圆,对焦ROI降级为中央40%(非全图)");
  229. int fineZHalf = Math.Max(200, ZHalf / 3); // 精对焦围绕粗焦点小范围
  230. int zstep = ZLayers > 1 ? 2 * fineZHalf / (ZLayers - 1) : 1;
  231. var curve = new List<(int z, double s)>();
  232. for (int i = 0; i < ZLayers; i++)
  233. {
  234. int z = Math.Max(0, coarseZ - fineZHalf) + zstep * i;
  235. _motor.VerticalMoveTo(z, ScanDelayMs);
  236. // P0-5: 每次移动后丢弃旧帧
  237. Grab(); // 丢弃第一帧
  238. var b = Grab(); // 使用第二帧
  239. double sc = Sharpness.Compute(b, W, H, roi);
  240. curve.Add((z, sc));
  241. OnStep?.Invoke($"精对焦 {i + 1}/{ZLayers} Z={z} 分={sc:F4}", circle, null);
  242. }
  243. // P1-3: 峰值平滑与插值 - 提升对焦精度
  244. // 3点滑动平均平滑
  245. var smoothed = new List<double>();
  246. for (int i = 0; i < curve.Count; i++)
  247. {
  248. double sum = curve[i].s;
  249. int cnt = 1;
  250. if (i > 0) { sum += curve[i - 1].s; cnt++; }
  251. if (i < curve.Count - 1) { sum += curve[i + 1].s; cnt++; }
  252. smoothed.Add(sum / cnt);
  253. }
  254. // 找平滑后的峰值
  255. double max = smoothed.Max();
  256. int pk = smoothed.IndexOf(max);
  257. double mean = smoothed.Average();
  258. // 抛物线插值峰顶(如果峰值不在边界)
  259. int focusZ = curve[pk].z;
  260. if (pk > 0 && pk < curve.Count - 1)
  261. {
  262. double y0 = smoothed[pk - 1], y1 = smoothed[pk], y2 = smoothed[pk + 1];
  263. double denominator = y0 - 2 * y1 + y2;
  264. if (Math.Abs(denominator) > 1e-9)
  265. {
  266. double delta = 0.5 * (y0 - y2) / denominator; // 抛物线顶点偏移
  267. focusZ = curve[pk].z + (int)(delta * zstep);
  268. }
  269. }
  270. r.FocusZ = focusZ;
  271. r.PeakSharp = max;
  272. r.PeakRatio = mean > 1e-9 ? max / mean : 1;
  273. // 检查对焦质量:峰过弱可能是空well或对焦失败
  274. if (r.PeakRatio < 1.2)
  275. {
  276. Log?.Invoke($"[well{well}] ⚠ 对焦峰过弱(ratio={r.PeakRatio:F2}),可能空well或对焦失败");
  277. r.Note += "对焦峰弱;";
  278. }
  279. _motor.VerticalMoveTo(r.FocusZ, ScanDelayMs);
  280. Log?.Invoke($"[well{well}] → 最清晰Z={r.FocusZ} 峰值={max:F4} max/mean={r.PeakRatio:F2} " +
  281. $"{(r.PeakRatio < 1.2 ? "(弱峰/可能空well)" : "✓有焦点")}");
  282. r.Note = $"{(r.CircleFound ? "" : "未检到well圆;")}{(r.PeakRatio < 1.2 ? "对焦峰弱;" : "")}";
  283. return r;
  284. }
  285. /// <summary>
  286. /// 粗对焦:围绕 centerZ±half 扫 layers 层,使用中央ROI清晰度找焦点。
  287. /// 目的是先把画面调清楚,让后续居中能稳定检出圆(对焦与居中耦合)。
  288. /// P0-6修复:使用中央40% ROI避免被背景边缘带偏。
  289. /// </summary>
  290. int CoarseFocus(int well, int centerZ, int half, int layers)
  291. {
  292. int zstep = layers > 1 ? 2 * half / (layers - 1) : 1;
  293. int bestZ = centerZ; double bestS = -1;
  294. // P0-6: 粗对焦使用中央40%区域ROI,避免背景干扰
  295. var centerROI = CenterRoi40();
  296. for (int i = 0; i < layers; i++)
  297. {
  298. int z = Math.Max(0, centerZ - half) + zstep * i;
  299. _motor.VerticalMoveTo(z, ScanDelayMs);
  300. // P0-5: 丢弃旧帧
  301. Grab();
  302. var b = Grab();
  303. double sc = Sharpness.Compute(b, W, H, centerROI); // 中央ROI(避免背景带偏)
  304. if (sc > bestS) { bestS = sc; bestZ = z; }
  305. OnStep?.Invoke($"粗对焦 {i + 1}/{layers} Z={z}", null, null);
  306. }
  307. return bestZ;
  308. }
  309. }
  310. }