CalibrationService.cs 18 KB

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