CalibrationService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using Cognex.VisionPro;
  2. using Cognex.VisionPro.ToolBlock;
  3. using MathNet.Numerics.LinearAlgebra;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Windows.Forms;
  11. using TeamAAS_VP.Core;
  12. using TeamAAS_VP.Core.Robots;
  13. using TeamAAS_VP.Enums;
  14. using TeamAAS_VP.Interfaces;
  15. using TeamAAS_VP.Models.Calibration;
  16. using TeamAAS_VP.Resources.Languages;
  17. namespace TeamAAS_VP.Services
  18. {
  19. /// <summary>
  20. /// Calibration 管理服务,负责校准文件的读取与保存以及像素到机器人位姿的转换。
  21. /// 线程安全:对内部集合的读/写通过 <see cref="_sync"/> 锁进行保护。
  22. /// 注意:构造函数不自动加载数据,调用者需要在合适时机调用 <see cref="LoadAll"/>。
  23. /// </summary>
  24. public class CalibrationService : ICalibrationService
  25. {
  26. IRobotService _robotService;
  27. /// <summary>
  28. /// 内部路径常量定义(相对路径)
  29. /// </summary>
  30. private static class Paths
  31. {
  32. public static readonly string CalibrationPath = "..//Calibration";
  33. public static string CalibrationListFilePath => Path.Combine(CalibrationPath ?? string.Empty, "CalibrationList.cfg");
  34. }
  35. // 同步锁对象,保护 _calibrations 的并发访问
  36. private readonly object _sync = new object();
  37. // 内存中的校准集合(用于 UI 绑定/管理)
  38. private ObservableCollection<CalibrationInfo> _calibrations = new ObservableCollection<CalibrationInfo>();
  39. /// <summary>
  40. /// 构造函数。注意:不在构造中自动加载校准,调用者应根据需要调用 <see cref="LoadAll"/>。
  41. /// </summary>
  42. public CalibrationService(IRobotService robotService)
  43. {
  44. _robotService = robotService ?? throw new ArgumentNullException(nameof(robotService));
  45. }
  46. /// <summary>
  47. /// 获取所有校准项的只读快照。
  48. /// 返回一个集合快照以避免外部对内部集合的直接修改。
  49. /// </summary>
  50. /// <returns>只读的 <see cref="CalibrationInfo"/> 集合</returns>
  51. public IReadOnlyCollection<CalibrationInfo> GetAllCalibrations()
  52. {
  53. lock (_sync)
  54. {
  55. // 返回当前集合的一个独立只读副本,避免并发问题
  56. return _calibrations.ToList().AsReadOnly();
  57. }
  58. }
  59. /// <summary>
  60. /// 根据 Id 获取单个校准信息。
  61. /// </summary>
  62. /// <param name="id">校准项的唯一标识</param>
  63. /// <returns>找到则返回 <see cref="CalibrationInfo"/>,否则返回 null</returns>
  64. public CalibrationInfo GetCalibration(Guid id)
  65. {
  66. lock (_sync)
  67. {
  68. return _calibrations.FirstOrDefault(c => c.Id == id);
  69. }
  70. }
  71. /// <summary>
  72. /// 添加或更新校准项:
  73. /// - 若 Id 存在则替换,否则追加并设置 Index
  74. /// - 写入单个校准 cfg 文件并更新索引文件
  75. /// - 保存或加载 ToolBlock(.vpp),若不存在则尝试从模板创建
  76. /// </summary>
  77. /// <param name="calib">要添加或更新的校准信息</param>
  78. /// <returns>保存后的 <see cref="CalibrationInfo"/>(可能为传入对象或修改后的对象);参数为 null 则返回 null</returns>
  79. public CalibrationInfo AddOrUpdateCalibration(CalibrationInfo calib)
  80. {
  81. if (calib == null) return null;
  82. lock (_sync)
  83. {
  84. var exist = _calibrations.FirstOrDefault(c => c.Id == calib.Id);
  85. if (exist != null)
  86. {
  87. // 替换已存在项(保持集合长度与 Index 不变)
  88. var idx = _calibrations.IndexOf(exist);
  89. _calibrations[idx] = calib;
  90. }
  91. else
  92. {
  93. // 新增项,Index 设为当前数量 + 1
  94. calib.Index = _calibrations.Count + 1;
  95. _calibrations.Add(calib);
  96. }
  97. }
  98. // 更新时间戳
  99. calib.DateTime = DateTime.Now;
  100. // 确保校准保存目录存在
  101. string folder = Path.Combine(Paths.CalibrationPath, calib.Name);
  102. string calibFile = Path.Combine(folder, calib.Name + ".cfg");
  103. if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
  104. // 写入单个校准文件(JSON)
  105. FileHelper.WriteJsonFile(calib, calibFile);
  106. // 更新索引列表(Id -> Name)并写入文件
  107. var list = new Dictionary<Guid, string>();
  108. lock (_sync)
  109. {
  110. foreach (var item in _calibrations)
  111. {
  112. list[item.Id] = item.Name;
  113. }
  114. }
  115. FileHelper.WriteJsonFile(list, Paths.CalibrationListFilePath);
  116. // 保存或加载 ToolBlock(.vpp)
  117. string prcPath = Path.Combine(folder, calib.Name + ".vpp");
  118. if (calib.ToolBlock != null)
  119. {
  120. // 已有 ToolBlock,直接保存
  121. VisionProFileHelper.SaveObjectToFileSafe(calib.ToolBlock, prcPath);
  122. }
  123. else
  124. {
  125. // 优先从当前目录加载已有 .vpp 文件,否则尝试从模板加载并保存
  126. if (File.Exists(prcPath))
  127. {
  128. calib.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
  129. }
  130. else if (File.Exists("..//Vision Template//Calibration.vpp"))
  131. {
  132. calib.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>("..//Vision Template//Calibration.vpp");
  133. VisionProFileHelper.SaveObjectToFileSafe(calib.ToolBlock, prcPath);
  134. }
  135. }
  136. return calib;
  137. }
  138. /// <summary>
  139. /// 根据 Id 移除校准项:
  140. /// - 从内存集合移除
  141. /// - 更新索引文件
  142. /// - 重新为剩余项排序 Index 并保存每个 cfg
  143. /// 注:不自动删除物理文件(除非有明确需求)
  144. /// </summary>
  145. /// <param name="id">要删除的校准项 Id</param>
  146. /// <returns>是否成功移除</returns>
  147. public bool RemoveCalibration(Guid id)
  148. {
  149. bool result = false;
  150. CalibrationInfo removed = null;
  151. lock (_sync)
  152. {
  153. removed = _calibrations.FirstOrDefault(c => c.Id == id);
  154. if (removed != null) result = _calibrations.Remove(removed);
  155. }
  156. // 更新索引文件(Id -> Name)
  157. var list = new Dictionary<Guid, string>();
  158. lock (_sync)
  159. {
  160. foreach (var item in _calibrations)
  161. {
  162. list[item.Id] = item.Name;
  163. }
  164. }
  165. FileHelper.WriteJsonFile(list, Paths.CalibrationListFilePath);
  166. // 删除后重新按 Index 排序并保存每个校准文件
  167. var calibs = _calibrations.OrderBy(c => c.Index).ToList();
  168. int index = 1;
  169. foreach (var item in calibs)
  170. {
  171. item.Index = index;
  172. // 保存更新后的 cfg 文件
  173. string folder = Path.Combine(Paths.CalibrationPath, item.Name);
  174. string calibFile = Path.Combine(folder, item.Name + ".cfg");
  175. FileHelper.WriteJsonFile(item, calibFile);
  176. index++;
  177. }
  178. // 用排序后的集合替换内存集合(注意:替换时未加锁是因为已在外部加锁或逻辑保证)
  179. _calibrations = new ObservableCollection<CalibrationInfo>(calibs);
  180. // 可选:删除物理文件和 toolblock(不自动删除)
  181. return result;
  182. }
  183. /// <summary>
  184. /// 加载所有校准数据:
  185. /// - 确保 CalibrationPath 存在
  186. /// - 读取索引文件,遍历项并加载各自的 cfg 与 .vpp(如果存在)
  187. /// - 忽略单个文件加载异常,继续加载其他文件
  188. /// </summary>
  189. public void LoadAll()
  190. {
  191. lock (_sync)
  192. {
  193. if (!Directory.Exists(Paths.CalibrationPath)) Directory.CreateDirectory(Paths.CalibrationPath);
  194. _calibrations.Clear();
  195. if (!File.Exists(Paths.CalibrationListFilePath))
  196. {
  197. // 若索引文件不存在,写入空索引并返回
  198. FileHelper.WriteJsonFile(new Dictionary<Guid, string>(), Paths.CalibrationListFilePath);
  199. return;
  200. }
  201. var list = FileHelper.ReadJsonFile<Dictionary<Guid, string>>(Paths.CalibrationListFilePath);
  202. if (list == null) return;
  203. foreach (var item in list)
  204. {
  205. try
  206. {
  207. // 使用 FilePath.CalibrationPath(项目全局路径)构建单个 cfg 路径
  208. string filePath = Path.Combine(FilePath.CalibrationPath, item.Value, item.Value + ".cfg");
  209. if (File.Exists(filePath))
  210. {
  211. var calib = FileHelper.ReadJsonFile<CalibrationInfo>(filePath);
  212. // 尝试加载对应的 .vpp ToolBlock
  213. string prcPath = Path.Combine(FilePath.CalibrationPath, calib.Name, calib.Name + ".vpp");
  214. if (File.Exists(prcPath))
  215. {
  216. calib.ToolBlock = VisionProFileHelper.LoadObjectFromFileSafe<CogToolBlock>(prcPath);
  217. }
  218. _calibrations.Add(calib);
  219. }
  220. }
  221. catch
  222. {
  223. // 忽略单个文件错误,继续加载其他文件
  224. }
  225. }
  226. }
  227. }
  228. /// <summary>
  229. /// 将内存中的所有校准保存到文件:
  230. /// - 为每个校准创建目录并写入 cfg
  231. /// - 若有 ToolBlock,则保存 .vpp
  232. /// - 写入索引文件
  233. /// </summary>
  234. public void SaveAll()
  235. {
  236. lock (_sync)
  237. {
  238. var list = new Dictionary<Guid, string>();
  239. foreach (var item in _calibrations)
  240. {
  241. list[item.Id] = item.Name;
  242. string folder = Path.Combine(FilePath.CalibrationPath, item.Name);
  243. if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
  244. string filePath = Path.Combine(folder, item.Name + ".cfg");
  245. FileHelper.WriteJsonFile(item, filePath);
  246. if (item.ToolBlock != null)
  247. {
  248. string prcPath = Path.Combine(folder, item.Name + ".vpp");
  249. VisionProFileHelper.SaveObjectToFileSafe(item.ToolBlock, prcPath);
  250. }
  251. }
  252. FileHelper.WriteJsonFile(list, Paths.CalibrationListFilePath);
  253. }
  254. }
  255. /// <summary>
  256. /// 校准转换:将像素坐标转换为机器人位置坐标(X,Y)及角度 U。
  257. /// 逻辑摘要:
  258. /// 1. 使用 calib.AffineTransformationMaterial 构建 3x3 仿射矩阵,将像素 [X,Y,1] 映射到机器人坐标系(单位:mm/像素转换后)。
  259. /// 2. 根据摄像机安装方式(CameraMount)进行不同的后处理:
  260. /// - MobileJ4: 采用基于 MarkPoint 的旋转矩阵,将像素直接转换的点旋转并平移到机器人当前 TOOL0 下的位置
  261. /// - MobileDown_XYPlatform: 类似 MobileJ4,但当前实现中角度置为 0(不旋转)
  262. /// - 其他情况:如果提供 robotCoord,则通过 ToolCoord 计算工具坐标(考虑机器人品牌对角度符号的影响)
  263. /// 3. 对于某些 CameraMount,输入角度需要取反(例如 FixedDown、MobileJ2、MobileJ4),以匹配机器人坐标系习惯
  264. /// </summary>
  265. /// <param name="pixelCoord">像素坐标及方向:(X, Y, angle)。angle 表示图像中测量的角度(度)</param>
  266. /// <param name="robotCoord">机器人当前位姿数组,通常为 [X, Y, U],可为 null(视场景而定)</param>
  267. /// <param name="calib">要使用的校准数据</param>
  268. /// <param name="robotBrand">机器人品牌,用于处理角度符号等差异</param>
  269. /// <returns>
  270. /// 返回元组 (IsSucceed, X, Y, U):
  271. /// - IsSucceed: 总是 true(当前实现未对数学运算做失败判定),调用者可根据需要扩展错误处理
  272. /// - X, Y: 转换后的机器人坐标(单位同 calib 所用单位)
  273. /// - U: 角度(经过可能的符号调整)
  274. /// </returns>
  275. public (bool IsSucceed, double X, double Y, double U) ConvertPixelToPosition((double X, double Y, double angle) pixelCoord, double[] robotCoord, CalibrationInfo calib, RobotBrand robotBrand = RobotBrand.Default)
  276. {
  277. double angle = pixelCoord.angle;
  278. // 从校准数据获取仿射变换矩阵(3x3)
  279. Matrix<double> matrix = Matrix<double>.Build.DenseOfArray(calib.AffineTransformationMaterial);
  280. // 某些安装方式需要取反角度以匹配机器人坐标系定义
  281. if (calib.CameraMount == CameraMount.FixedDown || calib.CameraMount == CameraMount.MobileJ2 || calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform || calib.CameraMount == CameraMount.MobileDown_IndependentXYPlatform)
  282. {
  283. angle *= -1;
  284. }
  285. // 将像素坐标通过仿射矩阵转换到机器人坐标(rpos 是长度 3 的向量:[X, Y, w],通常 w 为 1)
  286. var rpos = matrix * Vector<double>.Build.Dense(new double[] { pixelCoord.X, pixelCoord.Y, 1 });
  287. // 针对不同的 CameraMount 做进一步坐标变换
  288. if (calib.CameraMount == Enums.CameraMount.MobileJ4)
  289. {
  290. // 当 CameraMount 为 MobileJ4 时:
  291. // - rpos 的前两维表示像素->mm 转换后的点 (Robot_X, Robot_Y)
  292. // - 需要基于机器人当前 TOOL0 坐标以及 MarkPoint 的角度进行旋转和平移
  293. double Robot_X = rpos[0];
  294. double Robot_Y = rpos[1];
  295. // 机器人当前 TOOL0 下的位姿
  296. double curpos_x = robotCoord[0];
  297. double curpos_y = robotCoord[1];
  298. double curpos_u = robotCoord[2];
  299. // 旋转角(弧度) = (curpos_u - calib.MarkPoint.U) * PI / 180
  300. double angle1 = Math.PI * (curpos_u - calib.MarkPoint.U) / 180;
  301. // 2x2 旋转矩阵
  302. Matrix<double> rotationMatrix = Matrix<double>.Build.DenseOfArray(new double[,]
  303. {
  304. { Math.Cos(angle1), -Math.Sin(angle1) },
  305. { Math.Sin(angle1), Math.Cos(angle1) }
  306. });
  307. // 将相对向量 p3 旋转并平移到当前工具坐标系下
  308. Vector<double> p3 = Vector<double>.Build.Dense(new double[] { Robot_X - calib.CalibPoints[0].Robot.X, Robot_Y - calib.CalibPoints[0].Robot.Y });
  309. Vector<double> phere = Vector<double>.Build.Dense(new double[] { curpos_x, curpos_y });
  310. var cc = rotationMatrix * p3 + phere;
  311. rpos = Vector<double>.Build.Dense(new double[] { cc[0], cc[1] });
  312. }
  313. else if (calib.CameraMount == Enums.CameraMount.MobileDown_XYPlatform)
  314. {
  315. // MobileDown_XYPlatform 模式下,当前实现与 MobileJ4 类似,但角度暂时设为 0(不旋转)
  316. double Robot_X = rpos[0];
  317. double Robot_Y = rpos[1];
  318. double curpos_x = robotCoord[0];
  319. double curpos_y = robotCoord[1];
  320. double curpos_u = robotCoord[2];
  321. // 角度暂用 0(如有需要可基于 curpos_u - calib.MarkPoint.U 做旋转)
  322. double angle1 = 0;
  323. Matrix<double> rotationMatrix = Matrix<double>.Build.DenseOfArray(new double[,]
  324. {
  325. { Math.Cos(angle1), -Math.Sin(angle1) },
  326. { Math.Sin(angle1), Math.Cos(angle1) }
  327. });
  328. Vector<double> p3 = Vector<double>.Build.Dense(new double[] { Robot_X - calib.CalibPoints[0].Robot.X, Robot_Y - calib.CalibPoints[0].Robot.Y });
  329. Vector<double> phere = Vector<double>.Build.Dense(new double[] { curpos_x, curpos_y });
  330. var cc = rotationMatrix * p3 + phere;
  331. rpos = Vector<double>.Build.Dense(new double[] { cc[0], cc[1] }); // Mark 点在 tool0 下的坐标
  332. }
  333. else if (calib.CameraMount == Enums.CameraMount.MobileDown_IndependentXYPlatform)
  334. {
  335. //获取相机对应的移动模组的编号
  336. int moduleIndex = calib.CameraMotionModuleIndex;
  337. //获取机器人对象
  338. XYZU_Robot robot = _robotService.GetRobot(calib.RobotId) as XYZU_Robot;
  339. //获取当前移动模组的位置
  340. var movePos = robot?.GetCameraPos(moduleIndex);
  341. //将此时的坐标转换成独立模组坐标系下的坐标
  342. //旋转矩阵
  343. Matrix<double> R = Matrix<double>.Build.DenseOfArray(calib.IndependentDownCameraMotionModuleRotationMatrix);
  344. //平移矩阵
  345. Matrix<double> T = Matrix<double>.Build.DenseOfArray(calib.IndependentDownCameraMotionModuleTranslationMatrix);
  346. //平移向量
  347. Vector<double> PT = Vector<double>.Build.Dense(new double[] { T[0, 2], T[1, 2] });
  348. Vector<double> p100 = Vector<double>.Build.Dense(new double[] { calib.IndependentDownCameraMotionModulePoint.X, calib.IndependentDownCameraMotionModulePoint.Y });
  349. Vector<double> p101 = Vector<double>.Build.Dense(new double[] { movePos.X, movePos.Y });
  350. //计算独立模组坐标系下的坐标
  351. Vector<double> pl1 = R.Inverse() * (rpos - PT);
  352. Vector<double> pl2 = pl1 + (p101 - p100);
  353. //转换回机器人坐标系下的坐标
  354. var finalrpos = R * pl2 + PT;
  355. return (true, finalrpos[0], finalrpos[1], angle);
  356. }
  357. else
  358. {
  359. // 其他 CameraMount:如果提供了 robotCoord,则将仿射变换得到的点转换为工具坐标
  360. if (robotCoord != null)
  361. {
  362. double curposX = robotCoord[0];
  363. double curposY = robotCoord[1];
  364. double curposU = robotCoord[2];
  365. // 使用 ToolCoord 计算工具坐标(ToolCoord 内封装了从机器人基坐标到工具坐标的数学)
  366. ToolCoord tool = new ToolCoord();
  367. // Schneider 机器人角度符号可能与其他品牌相反,做兼容处理
  368. if (robotBrand == RobotBrand.Schneider)
  369. {
  370. curposU *= -1;
  371. }
  372. // 计算工具坐标并将 rpos 替换为工具坐标的 X,Y
  373. tool.ComputeTool(curposX, curposY, curposU, rpos[0], rpos[1]);
  374. rpos = Vector<double>.Build.Dense(new double[] { tool.X, tool.Y });
  375. }
  376. }
  377. // 返回最终结果,IsSucceed 在当前实现中总为 true(可根据需要扩展)
  378. return (true, rpos[0], rpos[1], angle);
  379. }
  380. /// <summary>
  381. /// 通过 calibId 获取校准并执行像素->位置转换。
  382. /// </summary>
  383. /// <param name="pixelCoord">像素坐标及角度 (X, Y, angle)</param>
  384. /// <param name="robotCoord">机器人当前位姿数组 [X, Y, U]</param>
  385. /// <param name="calibId">校准项 Id</param>
  386. /// <param name="robotBrand">机器人品牌(可选)</param>
  387. /// <returns>返回 (IsSucceed, X, Y, U)</returns>
  388. public (bool IsSucceed, double X, double Y, double U) ConvertPixelToPosition((double X, double Y, double angle) pixelCoord, double[] robotCoord, Guid calibId, RobotBrand robotBrand = RobotBrand.Default)
  389. {
  390. var calib = GetCalibration(calibId);
  391. if (calib == null)
  392. {
  393. // 若未找到校准数据,返回失败标志
  394. return (false, 0, 0, 0);
  395. }
  396. var result = ConvertPixelToPosition(pixelCoord, robotCoord, calib, robotBrand);
  397. return result;
  398. }
  399. /// <summary>
  400. /// Dispose 时保存所有校准数据并抑制终结化。
  401. /// </summary>
  402. public void Dispose()
  403. {
  404. SaveAll();
  405. GC.SuppressFinalize(this);
  406. }
  407. }
  408. }