IKapCamera.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. using Cognex.VisionPro;
  2. using IKapCDotNet;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Diagnostics;
  7. using System.Drawing;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using TeamAAS_VP.Core.IKapMethod;
  14. using TeamAAS_VP.Enums;
  15. using TeamAAS_VP.Interfaces;
  16. using TeamAAS_VP.Models;
  17. namespace TeamAAS_VP.Core.Cameras
  18. {
  19. public class IKapCamera : ICamera, INotifyPropertyChanged
  20. {
  21. #region 字段
  22. private IKDevice _ikDevice;
  23. private Thread _receiveThread;
  24. private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
  25. private readonly object _stateLock = new object();
  26. private readonly object _imageLock = new object();
  27. private bool _isGrabbing;
  28. private ICogImage _currentImage;
  29. private bool _isConnected;
  30. private string _errorMessage;
  31. private TimeSpan _totalTime;
  32. private long _imageWidth;
  33. private long _imageHeight;
  34. private uint _imageSize;
  35. private IntPtr _userBuffer = IntPtr.Zero;
  36. // 新增:图像格式信息
  37. private uint _pixelFormat; // 像素格式
  38. private int _pixelDepth; // 像素深度(位)
  39. private int _channelDepth; // 通道深度
  40. private uint _channels; // 通道数
  41. private bool _isColor; // 是否是彩色图像
  42. private int _bayerPattern; // Bayer格式(0:非Bayer, 1:BGGR, 2:RGGB, 3:GBRG, 4:GRBG)
  43. private StringBuilder _pixelFormatString = new StringBuilder(128);
  44. #endregion
  45. #region 属性
  46. public string Name { get; private set; }
  47. public Guid ID { get; private set; }
  48. public int Index { get; set; }
  49. public CameraBrand CameraBrand => CameraBrand.IKap;
  50. public bool IsFindByIp { get; private set; }
  51. public string ManufacturerName { get; private set; }
  52. public string ModelName { get; private set; }
  53. public string SerialNumber { get; private set; }
  54. public string CameraIp { get; private set; }
  55. public CameraType CameraType { get; private set; }
  56. public bool Is3D => false;
  57. public UInt32 ImageWidth => (UInt32)_imageWidth;
  58. public UInt32 ImageHeight => (UInt32)_imageHeight;
  59. public bool IsGrabbing
  60. {
  61. get => _isGrabbing;
  62. private set => SetProperty(ref _isGrabbing, value);
  63. }
  64. public ICogImage Image
  65. {
  66. get => _currentImage;
  67. private set => SetProperty(ref _currentImage, value);
  68. }
  69. public bool IsConnected
  70. {
  71. get => _isConnected;
  72. private set => SetProperty(ref _isConnected, value);
  73. }
  74. public TimeSpan TotalTime
  75. {
  76. get => _totalTime;
  77. private set => SetProperty(ref _totalTime, value);
  78. }
  79. public string ErrorMessage
  80. {
  81. get => _errorMessage;
  82. private set => SetProperty(ref _errorMessage, value);
  83. }
  84. public int DeviceIndex { get; private set; }
  85. public int BoardIndex { get; private set; }
  86. public int DeviceType { get; private set; }
  87. #endregion
  88. #region 事件
  89. public event Action<ICogImage, TimeSpan, string, Guid> ImageCallbackEvent;
  90. public event Action<Guid, bool> CameraConnectChangedEvent;
  91. #endregion
  92. #region 构造函数
  93. public IKapCamera(Guid id, int index, string name, string serialNumber, string cameraIp, bool isFindByIp)
  94. {
  95. ID = id;
  96. Name = name ?? serialNumber;
  97. Index = index;
  98. SerialNumber = serialNumber;
  99. CameraIp = cameraIp;
  100. IsFindByIp = isFindByIp;
  101. _ikDevice = new IKDevice();
  102. DeviceIndex = -1;
  103. BoardIndex = -1;
  104. _isColor = false;
  105. _pixelDepth = 8;
  106. _channels = 1;
  107. }
  108. public IKapCamera(Guid id, int deviceIndex, int boardIndex, string name, string serialNumber)
  109. {
  110. ID = id;
  111. Name = name;
  112. Index = deviceIndex;
  113. SerialNumber = serialNumber;
  114. DeviceIndex = deviceIndex;
  115. BoardIndex = boardIndex;
  116. IsFindByIp = false;
  117. _ikDevice = new IKDevice();
  118. _isColor = false;
  119. _pixelDepth = 8;
  120. _channels = 1;
  121. }
  122. #endregion
  123. #region 静态方法
  124. /// <summary>
  125. /// 获取所有IKap相机设备
  126. /// </summary>
  127. public static CameraInfo[] GetDevices()
  128. {
  129. List<CameraInfo> cameras = new List<CameraInfo>();
  130. try
  131. {
  132. // 初始化IKap
  133. uint res = IKapC.ItkManInitialize();
  134. if (!CheckIKapC(res))
  135. {
  136. LogHelper.WriteLogInfo("IKap初始化失败");
  137. return cameras.ToArray();
  138. }
  139. // 获取设备数量
  140. uint deviceCount = 0;
  141. res = IKapC.ItkManGetDeviceCount(ref deviceCount);
  142. if (!CheckIKapC(res) || deviceCount == 0)
  143. {
  144. return cameras.ToArray();
  145. }
  146. ITKDEV_INFO devInfo = new ITKDEV_INFO();
  147. ITKGIGEDEV_INFO gvDevInfo = new ITKGIGEDEV_INFO();
  148. ITK_U3V_DEV_INFO u3vDevInfo = new ITK_U3V_DEV_INFO();
  149. ITK_CXP_DEV_INFO cxpDevInfo = new ITK_CXP_DEV_INFO();
  150. ITK_CL_DEV_INFO clDevInfo = new ITK_CL_DEV_INFO();
  151. ITK_GVB_DEV_INFO gvbDevInfo = new ITK_GVB_DEV_INFO();
  152. for (uint i = 0; i < deviceCount; i++)
  153. {
  154. res = IKapC.ItkManGetDeviceInfo(i, devInfo);
  155. if (!CheckIKapC(res)) continue;
  156. CameraInfo cameraInfo = new CameraInfo
  157. {
  158. CameraNo = (int)i + 1,
  159. CameraBrand = CameraBrand.IKap,
  160. Model = devInfo.ModelName,
  161. SerialNumber = devInfo.SerialNumber ?? "",
  162. CameraName = devInfo.FullName,
  163. ManufacturerName = devInfo.VendorName,
  164. IsFindByIp = false
  165. };
  166. if (devInfo.DeviceClass.CompareTo("GigEVision") == 0)
  167. {
  168. res = IKapC.ItkManGetGigEDeviceInfo(i, gvDevInfo);
  169. if (CheckIKapC(res))
  170. {
  171. cameraInfo.CameraType = CameraType.GIGE;
  172. cameraInfo.CameraIp = gvDevInfo.Ip;
  173. cameraInfo.IsFindByIp = true;
  174. }
  175. }
  176. else if (devInfo.DeviceClass.CompareTo("USB3Vision") == 0)
  177. {
  178. res = IKapC.ItkManGetU3VDeviceInfo(i, u3vDevInfo);
  179. if (CheckIKapC(res))
  180. {
  181. cameraInfo.CameraType = CameraType.USB;
  182. }
  183. }
  184. else if (devInfo.DeviceClass.CompareTo("GigEVisionBoard") == 0)
  185. {
  186. res = IKapC.ItkManGetGVBDeviceInfo(i, gvbDevInfo);
  187. if (CheckIKapC(res))
  188. {
  189. cameraInfo.CameraType = CameraType.GIGE;
  190. cameraInfo.CameraIp = gvbDevInfo.Ip;
  191. cameraInfo.IsFindByIp = true;
  192. }
  193. }
  194. cameras.Add(cameraInfo);
  195. }
  196. }
  197. catch (Exception ex)
  198. {
  199. LogHelper.WriteLogError("搜索IKap相机列表时出错!", ex);
  200. }
  201. return cameras.ToArray();
  202. }
  203. /// <summary>
  204. /// 检查IKap SDK返回状态
  205. /// </summary>
  206. private static bool CheckIKapC(uint res)
  207. {
  208. if (res != IKapC.ITKSTATUS_OK)
  209. {
  210. LogHelper.WriteLogInfo($"IKap错误码: {res:X8}");
  211. return false;
  212. }
  213. return true;
  214. }
  215. #endregion
  216. #region 公共方法
  217. /// <summary>
  218. /// 打开相机
  219. /// </summary>
  220. public bool OpenDevice()
  221. {
  222. _operationSemaphore.Wait();
  223. try
  224. {
  225. if (_ikDevice == null)
  226. {
  227. _ikDevice = new IKDevice();
  228. }
  229. if (_ikDevice.isOpen())
  230. {
  231. IsConnected = true;
  232. return true;
  233. }
  234. // 初始化IKap
  235. uint res = IKapC.ItkManInitialize();
  236. if (!CheckIKapC(res))
  237. {
  238. LogHelper.WriteLogInfo("IKap初始化失败");
  239. return false;
  240. }
  241. // 查找并打开设备(代码保持不变)
  242. bool deviceFound = false;
  243. uint deviceCount = 0;
  244. res = IKapC.ItkManGetDeviceCount(ref deviceCount);
  245. if (!CheckIKapC(res))
  246. {
  247. ErrorMessage = "获取设备数量失败";
  248. return false;
  249. }
  250. ITKDEV_INFO devInfo = new ITKDEV_INFO();
  251. for (uint i = 0; i < deviceCount; i++)
  252. {
  253. res = IKapC.ItkManGetDeviceInfo(i, devInfo);
  254. if (!CheckIKapC(res)) continue;
  255. if (IsFindByIp && !string.IsNullOrEmpty(CameraIp))
  256. {
  257. if (devInfo.DeviceClass.CompareTo("GigEVision") == 0)
  258. {
  259. ITKGIGEDEV_INFO gvDevInfo = new ITKGIGEDEV_INFO();
  260. res = IKapC.ItkManGetGigEDeviceInfo(i, gvDevInfo);
  261. if (CheckIKapC(res))
  262. {
  263. string deviceIp = gvDevInfo.Ip;
  264. if (deviceIp == CameraIp)
  265. {
  266. DeviceIndex = (int)i;
  267. BoardIndex = 0;
  268. deviceFound = true;
  269. break;
  270. }
  271. }
  272. }
  273. }
  274. else if (!string.IsNullOrEmpty(SerialNumber) && devInfo.SerialNumber == SerialNumber)
  275. {
  276. DeviceIndex = (int)i;
  277. BoardIndex = 0;
  278. deviceFound = true;
  279. break;
  280. }
  281. else if (DeviceIndex >= 0 && (int)i == DeviceIndex)
  282. {
  283. deviceFound = true;
  284. break;
  285. }
  286. }
  287. if (!deviceFound)
  288. {
  289. ErrorMessage = "未找到匹配的相机设备";
  290. return false;
  291. }
  292. bool opened = _ikDevice.openDevice(DeviceIndex, BoardIndex);
  293. if (!opened)
  294. {
  295. ErrorMessage = "打开设备失败";
  296. return false;
  297. }
  298. /* 获取采集卡图像宽度 */
  299. int width = 0;
  300. var ret = IKapBoardDotNet.IKapBoard.IKapGetInfo(_ikDevice.m_pBoard, (uint)IKapBoardDotNet.IKapBoard.IKP_IMAGE_WIDTH, ref width);
  301. /* 获取采集卡图像高度 */
  302. int height = 0;
  303. ret = IKapBoardDotNet.IKapBoard.IKapGetInfo(_ikDevice.m_pBoard, (uint)IKapBoardDotNet.IKapBoard.IKP_IMAGE_HEIGHT, ref height);
  304. // 获取图像尺寸和格式信息
  305. _imageWidth = _ikDevice.m_nWidth = width;
  306. _imageHeight = _ikDevice.m_nHeight = height;
  307. // 获取图像格式信息
  308. GetImageFormatInfo();
  309. ManufacturerName = _ikDevice.m_devName ?? "";
  310. ModelName = _ikDevice.m_devName ?? "";
  311. IsConnected = true;
  312. CameraConnectChangedEvent?.Invoke(ID, true);
  313. ErrorMessage = "";
  314. return true;
  315. }
  316. catch (Exception ex)
  317. {
  318. ErrorMessage = ex.Message;
  319. LogHelper.WriteLogError("打开IKap相机失败", ex);
  320. return false;
  321. }
  322. finally
  323. {
  324. _operationSemaphore.Release();
  325. }
  326. }
  327. /// <summary>
  328. /// 异步打开相机
  329. /// </summary>
  330. public Task<bool> OpenDeviceAsync()
  331. {
  332. return Task.Run(() => OpenDevice());
  333. }
  334. /// <summary>
  335. /// 关闭相机
  336. /// </summary>
  337. public void CloseDevice()
  338. {
  339. _operationSemaphore.Wait();
  340. try
  341. {
  342. StopGrabbing();
  343. if (_ikDevice != null && _ikDevice.isOpen())
  344. {
  345. _ikDevice.closeDevice();
  346. }
  347. // 释放用户缓冲区
  348. if (_userBuffer != IntPtr.Zero)
  349. {
  350. Marshal.FreeHGlobal(_userBuffer);
  351. _userBuffer = IntPtr.Zero;
  352. }
  353. IsConnected = false;
  354. CameraConnectChangedEvent?.Invoke(ID, false);
  355. }
  356. finally
  357. {
  358. _operationSemaphore.Release();
  359. }
  360. }
  361. // 注意:需要更新 Grab 方法中的图像获取部分
  362. public ICogImage Grab(bool isRealtime = true)
  363. {
  364. _operationSemaphore.Wait();
  365. try
  366. {
  367. Stopwatch sw = Stopwatch.StartNew();
  368. if (!IsConnected)
  369. {
  370. if (!OpenDevice())
  371. {
  372. return null;
  373. }
  374. }
  375. _ikDevice.releaseStream();
  376. // 创建流
  377. if (!_ikDevice.createStream())
  378. {
  379. ErrorMessage = "创建流失败";
  380. return null;
  381. }
  382. //开始采集前执行关闭操作,防止相机已经处于采集状态
  383. if (!_ikDevice.stopGrab())
  384. return null;
  385. // 开始采集单帧
  386. if (!_ikDevice.startGrab(1))
  387. {
  388. ErrorMessage = "开始采集失败";
  389. return null;
  390. }
  391. // 等待采集完成
  392. _ikDevice.waitGrab();
  393. // 获取图像数据
  394. lock (_imageLock)
  395. {
  396. if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
  397. {
  398. // 使用新的图像转换方法
  399. Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  400. _ikDevice.m_bUpdateImage = false;
  401. }
  402. }
  403. // 停止采集
  404. _ikDevice.stopGrab();
  405. _ikDevice.releaseStream();
  406. TotalTime = sw.Elapsed;
  407. if (Image == null)
  408. {
  409. ErrorMessage = "采集图像为空";
  410. }
  411. else
  412. {
  413. ErrorMessage = "";
  414. }
  415. return Image;
  416. }
  417. catch (Exception ex)
  418. {
  419. ErrorMessage = ex.Message;
  420. LogHelper.WriteLogError("采集图像失败", ex);
  421. return null;
  422. }
  423. finally
  424. {
  425. _operationSemaphore.Release();
  426. }
  427. }
  428. // 注意:需要更新 Grab 方法中的图像获取部分
  429. public ICogImage Grab2(bool isRealtime = true)
  430. {
  431. _operationSemaphore.Wait();
  432. try
  433. {
  434. Stopwatch sw = Stopwatch.StartNew();
  435. if (!IsConnected)
  436. {
  437. if (!OpenDevice())
  438. {
  439. return null;
  440. }
  441. }
  442. _ikDevice.releaseStream();
  443. // 创建流
  444. if (!_ikDevice.createStream())
  445. {
  446. ErrorMessage = "创建流失败";
  447. return null;
  448. }
  449. //开始采集前执行关闭操作,防止相机已经处于采集状态
  450. if (!_ikDevice.stopGrab())
  451. return null;
  452. // 开始采集单帧
  453. if (!_ikDevice.startGrab(1))
  454. {
  455. ErrorMessage = "开始采集失败";
  456. return null;
  457. }
  458. // 等待采集完成
  459. _ikDevice.waitGrab();
  460. // 获取图像数据
  461. lock (_imageLock)
  462. {
  463. if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
  464. {
  465. // 使用新的图像转换方法
  466. Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  467. _ikDevice.m_bUpdateImage = false;
  468. }
  469. }
  470. // 停止采集
  471. _ikDevice.stopGrab();
  472. _ikDevice.releaseStream();
  473. TotalTime = sw.Elapsed;
  474. if (Image == null)
  475. {
  476. ErrorMessage = "采集图像为空";
  477. }
  478. else
  479. {
  480. ErrorMessage = "";
  481. }
  482. return Image;
  483. }
  484. catch (Exception ex)
  485. {
  486. ErrorMessage = ex.Message;
  487. LogHelper.WriteLogError("采集图像失败", ex);
  488. return null;
  489. }
  490. finally
  491. {
  492. _operationSemaphore.Release();
  493. }
  494. }
  495. /// <summary>
  496. /// 开始实时采集
  497. /// </summary>
  498. public void StartGrabbing()
  499. {
  500. lock (_stateLock)
  501. {
  502. if (_isGrabbing) return;
  503. _isGrabbing = true;
  504. }
  505. if (!IsConnected)
  506. {
  507. OpenDevice();
  508. }
  509. _receiveThread = new Thread(GrabbingThreadProc) { IsBackground = true };
  510. _receiveThread.Start();
  511. }
  512. /// <summary>
  513. /// 停止实时采集
  514. /// </summary>
  515. public void StopGrabbing()
  516. {
  517. lock (_stateLock)
  518. {
  519. _isGrabbing = false;
  520. }
  521. Thread.Sleep(100);
  522. if (_receiveThread != null && _receiveThread.IsAlive)
  523. {
  524. try
  525. {
  526. _receiveThread.Join(1000);
  527. }
  528. catch { }
  529. _receiveThread = null;
  530. }
  531. if (_ikDevice != null && _ikDevice.m_bGrabingImage)
  532. {
  533. _ikDevice.stopGrab();
  534. _ikDevice.releaseStream();
  535. }
  536. }
  537. /// <summary>
  538. /// 设置曝光时间
  539. /// </summary>
  540. public bool SetExposureTime(float exposureTime)
  541. {
  542. _operationSemaphore.Wait();
  543. try
  544. {
  545. if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  546. {
  547. return false;
  548. }
  549. uint res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "ExposureTime", exposureTime);
  550. return CheckIKapC(res);
  551. }
  552. finally
  553. {
  554. _operationSemaphore.Release();
  555. }
  556. }
  557. /// <summary>
  558. /// 获取曝光时间
  559. /// </summary>
  560. public float GetExposureTime()
  561. {
  562. _operationSemaphore.Wait();
  563. try
  564. {
  565. if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  566. {
  567. return 0;
  568. }
  569. double value = 0;
  570. uint res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "ExposureTime", ref value);
  571. return CheckIKapC(res) ? (float)value : 0;
  572. }
  573. finally
  574. {
  575. _operationSemaphore.Release();
  576. }
  577. }
  578. /// <summary>
  579. /// 设置增益
  580. /// </summary>
  581. public bool SetGain(float gain)
  582. {
  583. //_operationSemaphore.Wait();
  584. //try
  585. //{
  586. // if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  587. // {
  588. // return false;
  589. // }
  590. // 尝试使用AnalogGain
  591. // uint res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "AnalogGain", gain);
  592. // if (!CheckIKapC(res))
  593. // {
  594. // 如果AnalogGain不支持,尝试Gain
  595. // res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "Gain", gain);
  596. // return CheckIKapC(res);
  597. // }
  598. // return true;
  599. //}
  600. //finally
  601. //{
  602. // _operationSemaphore.Release();
  603. //}
  604. return true;
  605. }
  606. /// <summary>
  607. /// 获取增益
  608. /// </summary>
  609. public float GetGain()
  610. {
  611. _operationSemaphore.Wait();
  612. try
  613. {
  614. if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  615. {
  616. return 0;
  617. }
  618. double value = 0;
  619. uint res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "AnalogGain", ref value);
  620. if (!CheckIKapC(res))
  621. {
  622. res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "Gain", ref value);
  623. if (!CheckIKapC(res))
  624. {
  625. return 0;
  626. }
  627. }
  628. return (float)value;
  629. }
  630. finally
  631. {
  632. _operationSemaphore.Release();
  633. }
  634. }
  635. /// <summary>
  636. /// 检查相机软件是否安装
  637. /// </summary>
  638. /// <returns></returns>
  639. public static (bool isInstalled, string version) CheckSoftwareInstalled()
  640. {
  641. return (true, "");
  642. }
  643. #endregion
  644. #region 私有方法
  645. // 更新实时采集线程
  646. private void GrabbingThreadProc()
  647. {
  648. try
  649. {
  650. if (!_ikDevice.createStream())
  651. {
  652. ErrorMessage = "创建流失败";
  653. return;
  654. }
  655. if (!_ikDevice.startGrab(0))
  656. {
  657. ErrorMessage = "开始连续采集失败";
  658. return;
  659. }
  660. while (_isGrabbing)
  661. {
  662. Stopwatch sw = Stopwatch.StartNew();
  663. int waitCount = 0;
  664. while (_isGrabbing && !_ikDevice.m_bUpdateImage && waitCount < 50)
  665. {
  666. Thread.Sleep(10);
  667. waitCount++;
  668. }
  669. if (_ikDevice.m_bUpdateImage)
  670. {
  671. lock (_imageLock)
  672. {
  673. if (_ikDevice.m_pUserBuffer != IntPtr.Zero)
  674. {
  675. // 使用新的图像转换方法
  676. Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  677. _ikDevice.m_bUpdateImage = false;
  678. }
  679. }
  680. TotalTime = sw.Elapsed;
  681. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage, ID);
  682. }
  683. Thread.Sleep(1);
  684. }
  685. }
  686. catch (Exception ex)
  687. {
  688. LogHelper.WriteLogError("实时采集线程异常", ex);
  689. ErrorMessage = ex.Message;
  690. }
  691. finally
  692. {
  693. _ikDevice.stopGrab();
  694. _ikDevice.releaseStream();
  695. IsGrabbing = false;
  696. }
  697. }
  698. #endregion
  699. #region 私有方法 - 图像转换
  700. /// <summary>
  701. /// 获取图像像素格式信息
  702. /// </summary>
  703. private bool GetImageFormatInfo()
  704. {
  705. try
  706. {
  707. if (_ikDevice.m_hDev.unused == 0)
  708. return false;
  709. uint res = IKapC.ITKSTATUS_OK;
  710. // 获取像素格式字符串
  711. uint pixelFormatSize = 128;
  712. res = IKapC.ItkDevToString(_ikDevice.m_hDev, "PixelFormat", _pixelFormatString, ref pixelFormatSize);
  713. if (!CheckIKapC(res))
  714. {
  715. LogHelper.WriteLogInfo("获取PixelFormat失败");
  716. return false;
  717. }
  718. // 获取像素格式值
  719. res = IKapC.ItkDevGetPixelFormatVal(_ikDevice.m_hDev, _pixelFormatString.ToString(), ref _pixelFormat);
  720. if (!CheckIKapC(res))
  721. {
  722. LogHelper.WriteLogInfo("获取PixelFormat值失败");
  723. return false;
  724. }
  725. // 获取通道深度(每个通道的位数)
  726. _channelDepth = (int)IKapC.ITKBUFFER_FORMAT_CHANNEL_BITS(_pixelFormat);
  727. // 获取像素深度(每个像素的总位数)
  728. _pixelDepth = (int)IKapC.ITKBUFFER_FORMAT_PIXEL_BITS(_pixelFormat);
  729. // 获取通道数
  730. _channels = (uint)(_pixelDepth / _channelDepth);
  731. // 判断是否为彩色图像
  732. string pixelFormatStr = _pixelFormatString.ToString().ToUpper();
  733. _isColor = pixelFormatStr.Contains("RGB") ||
  734. pixelFormatStr.Contains("BGR") ||
  735. pixelFormatStr.Contains("YUV") ||
  736. (_channels >= 3);
  737. // 检查是否为Bayer格式
  738. if (pixelFormatStr.Contains("BAYER"))
  739. {
  740. if (pixelFormatStr.Contains("BGGR"))
  741. _bayerPattern = 1;
  742. else if (pixelFormatStr.Contains("RGGB"))
  743. _bayerPattern = 2;
  744. else if (pixelFormatStr.Contains("GBRG"))
  745. _bayerPattern = 3;
  746. else if (pixelFormatStr.Contains("GRBG"))
  747. _bayerPattern = 4;
  748. _isColor = true; // Bayer格式最终会转换为彩色
  749. }
  750. LogHelper.WriteLogInfo($"图像格式: {_pixelFormatString}, 像素深度={_pixelDepth}, 通道数={_channels}, 彩色={_isColor}");
  751. return true;
  752. }
  753. catch (Exception ex)
  754. {
  755. LogHelper.WriteLogError("获取图像格式信息失败", ex);
  756. return false;
  757. }
  758. }
  759. /// <summary>
  760. /// 将原始缓冲区数据转换为ICogImage
  761. /// </summary>
  762. private ICogImage ConvertBufferToCogImage(IntPtr buffer)
  763. {
  764. if (buffer == IntPtr.Zero || _imageWidth <= 0 || _imageHeight <= 0)
  765. {
  766. return null;
  767. }
  768. try
  769. {
  770. int width = (int)_imageWidth;
  771. int height = (int)_imageHeight;
  772. ICogImage tempImage = null;
  773. // 处理Bayer格式
  774. IntPtr convertedBuffer = buffer;
  775. bool needFree = false;
  776. if (_bayerPattern != 0 && _pixelDepth == 8)
  777. {
  778. int rgbSize = width * height * 3;
  779. IntPtr rgbBuffer = Marshal.AllocHGlobal(rgbSize);
  780. if (IKDevice.Bayer2RGB(buffer, _pixelFormat, ref rgbBuffer,
  781. IKapC.ITKBUFFER_VAL_FORMAT_BGR888, width, height, _bayerPattern))
  782. {
  783. convertedBuffer = rgbBuffer;
  784. needFree = true;
  785. _isColor = true;
  786. _pixelDepth = 24;
  787. }
  788. else
  789. {
  790. Marshal.FreeHGlobal(rgbBuffer);
  791. return null;
  792. }
  793. }
  794. // 创建临时图像(可能只是引用数据)
  795. if (_isColor || _channels >= 3)
  796. {
  797. if (_pixelDepth == 24 || _pixelDepth == 8 * 3)
  798. {
  799. tempImage = CreateColorImage(convertedBuffer, width, height);
  800. }
  801. }
  802. else
  803. {
  804. if (_pixelDepth == 8)
  805. {
  806. tempImage = CreateGreyImage(convertedBuffer, width, height);
  807. }
  808. else if (_pixelDepth == 16)
  809. {
  810. tempImage = CreateGreyImage16(convertedBuffer, width, height);
  811. }
  812. }
  813. if (tempImage == null)
  814. {
  815. return null;
  816. }
  817. // ✅ 关键:强制创建独立副本
  818. ICogImage result = null;
  819. // 方法1:使用 CopyBase 创建可独立管理的副本
  820. if (tempImage is CogImage8Grey grey8Image)
  821. {
  822. result = grey8Image.CopyBase(CogImageCopyModeConstants.CopyPixels);
  823. }
  824. else if (tempImage is CogImage16Grey grey16Image)
  825. {
  826. result = grey16Image.CopyBase(CogImageCopyModeConstants.CopyPixels);
  827. }
  828. else if (tempImage is CogImage24PlanarColor colorImage)
  829. {
  830. result = colorImage.CopyBase(CogImageCopyModeConstants.CopyPixels);
  831. }
  832. else
  833. {
  834. // 方法2:转换为 Bitmap 再转回(最稳妥)
  835. using (Bitmap bitmap = tempImage.ToBitmap())
  836. {
  837. if (_isColor)
  838. {
  839. result = new CogImage24PlanarColor(bitmap);
  840. }
  841. else
  842. {
  843. result = new CogImage8Grey(bitmap);
  844. }
  845. }
  846. }
  847. // 释放临时图像(如果它是独立的对象)
  848. //if (tempImage != null && tempImage != result)
  849. //{
  850. // Marshal.ReleaseComObject(tempImage);
  851. //}
  852. //// ✅ 只有在确保图像数据已经被复制后,才能释放临时缓冲区
  853. //if (needFree && convertedBuffer != IntPtr.Zero)
  854. //{
  855. // Marshal.FreeHGlobal(convertedBuffer);
  856. //}
  857. return result;
  858. }
  859. catch (Exception ex)
  860. {
  861. LogHelper.WriteLogError("转换图像数据失败", ex);
  862. return null;
  863. }
  864. }
  865. /// <summary>
  866. /// 创建8位灰度图像
  867. /// </summary>
  868. private ICogImage CreateGreyImage(IntPtr buffer, int width, int height)
  869. {
  870. try
  871. {
  872. CogImage8Root greyRoot = new CogImage8Root();
  873. greyRoot.Initialize(width, height, buffer, width, null);
  874. CogImage8Grey greyImage = new CogImage8Grey();
  875. greyImage.SetRoot(greyRoot);
  876. return greyImage;
  877. }
  878. catch (Exception ex)
  879. {
  880. LogHelper.WriteLogError("创建8位灰度图像失败", ex);
  881. return null;
  882. }
  883. }
  884. /// <summary>
  885. /// 创建16位灰度图像
  886. /// </summary>
  887. private ICogImage CreateGreyImage16(IntPtr buffer, int width, int height)
  888. {
  889. try
  890. {
  891. // 使用CogImage16Grey(如果VisionPro支持)
  892. // 如果不支持,可以转换为8位
  893. CogImage16Root grey16Root = new CogImage16Root();
  894. grey16Root.Initialize(width, height, buffer, width * 2, null);
  895. CogImage16Grey grey16Image = new CogImage16Grey();
  896. grey16Image.SetRoot(grey16Root);
  897. return grey16Image;
  898. }
  899. catch
  900. {
  901. // 如果不支持16位,转换为8位
  902. int size = width * height;
  903. byte[] grey8Data = new byte[size];
  904. unsafe
  905. {
  906. ushort* src = (ushort*)buffer.ToPointer();
  907. for (int i = 0; i < size; i++)
  908. {
  909. grey8Data[i] = (byte)(src[i] >> 8);
  910. }
  911. }
  912. IntPtr grey8Buffer = Marshal.AllocHGlobal(size);
  913. Marshal.Copy(grey8Data, 0, grey8Buffer, size);
  914. CogImage8Root grey8Root = new CogImage8Root();
  915. grey8Root.Initialize(width, height, grey8Buffer, width, null);
  916. CogImage8Grey grey8Image = new CogImage8Grey();
  917. grey8Image.SetRoot(grey8Root);
  918. Marshal.FreeHGlobal(grey8Buffer);
  919. return grey8Image;
  920. }
  921. }
  922. /// <summary>
  923. /// 创建24位彩色图像(RGB/BGR)
  924. /// </summary>
  925. private ICogImage CreateColorImage(IntPtr buffer, int width, int height)
  926. {
  927. try
  928. {
  929. unsafe
  930. {
  931. byte* pixelData = (byte*)buffer.ToPointer();
  932. byte[] redPlane = new byte[width * height];
  933. byte[] greenPlane = new byte[width * height];
  934. byte[] bluePlane = new byte[width * height];
  935. // 假设是BGR格式(大多数相机使用BGR)
  936. for (int i = 0; i < width * height; i++)
  937. {
  938. bluePlane[i] = pixelData[3 * i];
  939. greenPlane[i] = pixelData[3 * i + 1];
  940. redPlane[i] = pixelData[3 * i + 2];
  941. }
  942. // 分配非托管内存
  943. IntPtr redPtr = Marshal.AllocHGlobal(redPlane.Length);
  944. IntPtr greenPtr = Marshal.AllocHGlobal(greenPlane.Length);
  945. IntPtr bluePtr = Marshal.AllocHGlobal(bluePlane.Length);
  946. Marshal.Copy(redPlane, 0, redPtr, redPlane.Length);
  947. Marshal.Copy(greenPlane, 0, greenPtr, greenPlane.Length);
  948. Marshal.Copy(bluePlane, 0, bluePtr, bluePlane.Length);
  949. CogImage8Root redRoot = new CogImage8Root();
  950. CogImage8Root greenRoot = new CogImage8Root();
  951. CogImage8Root blueRoot = new CogImage8Root();
  952. redRoot.Initialize(width, height, redPtr, width, null);
  953. greenRoot.Initialize(width, height, greenPtr, width, null);
  954. blueRoot.Initialize(width, height, bluePtr, width, null);
  955. CogImage24PlanarColor image = new CogImage24PlanarColor();
  956. image.SetRoots(redRoot, greenRoot, blueRoot);
  957. // 注意:这里分配的内存需要在图像使用完毕后释放
  958. // 但由于CogImage可能持有引用,需要妥善处理
  959. // 简单起见,先不释放,在实际使用中需要管理生命周期
  960. return image;
  961. }
  962. }
  963. catch (Exception ex)
  964. {
  965. LogHelper.WriteLogError("创建彩色图像失败", ex);
  966. return null;
  967. }
  968. }
  969. #endregion
  970. #region INotifyPropertyChanged
  971. public event PropertyChangedEventHandler PropertyChanged;
  972. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  973. {
  974. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  975. storage = value;
  976. RaisePropertyChanged(propertyName);
  977. return true;
  978. }
  979. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  980. {
  981. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  982. }
  983. #endregion
  984. }
  985. }