CalibrationEngine.cs 14 KB

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