IKapCamera.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
  394. {
  395. // 使用新的图像转换方法
  396. Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  397. _ikDevice.m_bUpdateImage = false;
  398. }
  399. // 获取图像数据
  400. //lock (_imageLock)
  401. //{
  402. // if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
  403. // {
  404. // // 使用新的图像转换方法
  405. // Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  406. // _ikDevice.m_bUpdateImage = false;
  407. // }
  408. //}
  409. // 停止采集
  410. _ikDevice.stopGrab();
  411. _ikDevice.releaseStream();
  412. TotalTime = sw.Elapsed;
  413. if (Image == null)
  414. {
  415. ErrorMessage = "采集图像为空";
  416. }
  417. else
  418. {
  419. ErrorMessage = "";
  420. }
  421. return Image;
  422. }
  423. catch (Exception ex)
  424. {
  425. ErrorMessage = ex.Message;
  426. LogHelper.WriteLogError("采集图像失败", ex);
  427. return null;
  428. }
  429. finally
  430. {
  431. // _operationSemaphore.Release();
  432. }
  433. }
  434. // 注意:需要更新 Grab 方法中的图像获取部分
  435. public ICogImage Grab2(bool isRealtime = true)
  436. {
  437. _operationSemaphore.Wait();
  438. try
  439. {
  440. Stopwatch sw = Stopwatch.StartNew();
  441. if (!IsConnected)
  442. {
  443. if (!OpenDevice())
  444. {
  445. return null;
  446. }
  447. }
  448. _ikDevice.releaseStream();
  449. // 创建流
  450. if (!_ikDevice.createStream())
  451. {
  452. ErrorMessage = "创建流失败";
  453. return null;
  454. }
  455. //开始采集前执行关闭操作,防止相机已经处于采集状态
  456. if (!_ikDevice.stopGrab())
  457. return null;
  458. // 开始采集单帧
  459. if (!_ikDevice.startGrab(1))
  460. {
  461. ErrorMessage = "开始采集失败";
  462. return null;
  463. }
  464. // 等待采集完成
  465. _ikDevice.waitGrab();
  466. // 获取图像数据
  467. lock (_imageLock)
  468. {
  469. if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
  470. {
  471. // 使用新的图像转换方法
  472. Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  473. _ikDevice.m_bUpdateImage = false;
  474. }
  475. }
  476. // 停止采集
  477. _ikDevice.stopGrab();
  478. _ikDevice.releaseStream();
  479. TotalTime = sw.Elapsed;
  480. if (Image == null)
  481. {
  482. ErrorMessage = "采集图像为空";
  483. }
  484. else
  485. {
  486. ErrorMessage = "";
  487. }
  488. return Image;
  489. }
  490. catch (Exception ex)
  491. {
  492. ErrorMessage = ex.Message;
  493. LogHelper.WriteLogError("采集图像失败", ex);
  494. return null;
  495. }
  496. finally
  497. {
  498. _operationSemaphore.Release();
  499. }
  500. }
  501. /// <summary>
  502. /// 开始实时采集
  503. /// </summary>
  504. public void StartGrabbing()
  505. {
  506. lock (_stateLock)
  507. {
  508. if (_isGrabbing) return;
  509. _isGrabbing = true;
  510. }
  511. if (!IsConnected)
  512. {
  513. OpenDevice();
  514. }
  515. _receiveThread = new Thread(GrabbingThreadProc) { IsBackground = true };
  516. _receiveThread.Start();
  517. }
  518. /// <summary>
  519. /// 停止实时采集
  520. /// </summary>
  521. public void StopGrabbing()
  522. {
  523. lock (_stateLock)
  524. {
  525. _isGrabbing = false;
  526. }
  527. Thread.Sleep(100);
  528. if (_receiveThread != null && _receiveThread.IsAlive)
  529. {
  530. try
  531. {
  532. _receiveThread.Join(1000);
  533. }
  534. catch { }
  535. _receiveThread = null;
  536. }
  537. if (_ikDevice != null && _ikDevice.m_bGrabingImage)
  538. {
  539. _ikDevice.stopGrab();
  540. _ikDevice.releaseStream();
  541. }
  542. }
  543. /// <summary>
  544. /// 设置曝光时间
  545. /// </summary>
  546. public bool SetExposureTime(float exposureTime)
  547. {
  548. _operationSemaphore.Wait();
  549. try
  550. {
  551. if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  552. {
  553. return false;
  554. }
  555. uint res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "ExposureTime", exposureTime);
  556. return CheckIKapC(res);
  557. }
  558. finally
  559. {
  560. _operationSemaphore.Release();
  561. }
  562. }
  563. /// <summary>
  564. /// 获取曝光时间
  565. /// </summary>
  566. public float GetExposureTime()
  567. {
  568. _operationSemaphore.Wait();
  569. try
  570. {
  571. if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  572. {
  573. return 0;
  574. }
  575. double value = 0;
  576. uint res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "ExposureTime", ref value);
  577. return CheckIKapC(res) ? (float)value : 0;
  578. }
  579. finally
  580. {
  581. _operationSemaphore.Release();
  582. }
  583. }
  584. /// <summary>
  585. /// 设置增益
  586. /// </summary>
  587. public bool SetGain(float gain)
  588. {
  589. //_operationSemaphore.Wait();
  590. //try
  591. //{
  592. // if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  593. // {
  594. // return false;
  595. // }
  596. // 尝试使用AnalogGain
  597. // uint res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "AnalogGain", gain);
  598. // if (!CheckIKapC(res))
  599. // {
  600. // 如果AnalogGain不支持,尝试Gain
  601. // res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "Gain", gain);
  602. // return CheckIKapC(res);
  603. // }
  604. // return true;
  605. //}
  606. //finally
  607. //{
  608. // _operationSemaphore.Release();
  609. //}
  610. return true;
  611. }
  612. /// <summary>
  613. /// 获取增益
  614. /// </summary>
  615. public float GetGain()
  616. {
  617. _operationSemaphore.Wait();
  618. try
  619. {
  620. if (!IsConnected || _ikDevice.m_hDev.unused == 0)
  621. {
  622. return 0;
  623. }
  624. double value = 0;
  625. uint res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "AnalogGain", ref value);
  626. if (!CheckIKapC(res))
  627. {
  628. res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "Gain", ref value);
  629. if (!CheckIKapC(res))
  630. {
  631. return 0;
  632. }
  633. }
  634. return (float)value;
  635. }
  636. finally
  637. {
  638. _operationSemaphore.Release();
  639. }
  640. }
  641. /// <summary>
  642. /// 检查相机软件是否安装
  643. /// </summary>
  644. /// <returns></returns>
  645. public static (bool isInstalled, string version) CheckSoftwareInstalled()
  646. {
  647. return (true, "");
  648. }
  649. #endregion
  650. #region 私有方法
  651. // 更新实时采集线程
  652. private void GrabbingThreadProc()
  653. {
  654. try
  655. {
  656. if (!_ikDevice.createStream())
  657. {
  658. ErrorMessage = "创建流失败";
  659. return;
  660. }
  661. if (!_ikDevice.startGrab(0))
  662. {
  663. ErrorMessage = "开始连续采集失败";
  664. return;
  665. }
  666. while (_isGrabbing)
  667. {
  668. Stopwatch sw = Stopwatch.StartNew();
  669. int waitCount = 0;
  670. while (_isGrabbing && !_ikDevice.m_bUpdateImage && waitCount < 50)
  671. {
  672. Thread.Sleep(10);
  673. waitCount++;
  674. }
  675. if (_ikDevice.m_bUpdateImage)
  676. {
  677. lock (_imageLock)
  678. {
  679. if (_ikDevice.m_pUserBuffer != IntPtr.Zero)
  680. {
  681. // 使用新的图像转换方法
  682. Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
  683. _ikDevice.m_bUpdateImage = false;
  684. }
  685. }
  686. TotalTime = sw.Elapsed;
  687. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage, ID);
  688. }
  689. Thread.Sleep(1);
  690. }
  691. }
  692. catch (Exception ex)
  693. {
  694. LogHelper.WriteLogError("实时采集线程异常", ex);
  695. ErrorMessage = ex.Message;
  696. }
  697. finally
  698. {
  699. _ikDevice.stopGrab();
  700. _ikDevice.releaseStream();
  701. IsGrabbing = false;
  702. }
  703. }
  704. #endregion
  705. #region 私有方法 - 图像转换
  706. /// <summary>
  707. /// 获取图像像素格式信息
  708. /// </summary>
  709. private bool GetImageFormatInfo()
  710. {
  711. try
  712. {
  713. if (_ikDevice.m_hDev.unused == 0)
  714. return false;
  715. uint res = IKapC.ITKSTATUS_OK;
  716. // 获取像素格式字符串
  717. uint pixelFormatSize = 128;
  718. res = IKapC.ItkDevToString(_ikDevice.m_hDev, "PixelFormat", _pixelFormatString, ref pixelFormatSize);
  719. if (!CheckIKapC(res))
  720. {
  721. LogHelper.WriteLogInfo("获取PixelFormat失败");
  722. return false;
  723. }
  724. // 获取像素格式值
  725. res = IKapC.ItkDevGetPixelFormatVal(_ikDevice.m_hDev, _pixelFormatString.ToString(), ref _pixelFormat);
  726. if (!CheckIKapC(res))
  727. {
  728. LogHelper.WriteLogInfo("获取PixelFormat值失败");
  729. return false;
  730. }
  731. // 获取通道深度(每个通道的位数)
  732. _channelDepth = (int)IKapC.ITKBUFFER_FORMAT_CHANNEL_BITS(_pixelFormat);
  733. // 获取像素深度(每个像素的总位数)
  734. _pixelDepth = (int)IKapC.ITKBUFFER_FORMAT_PIXEL_BITS(_pixelFormat);
  735. // 获取通道数
  736. _channels = (uint)(_pixelDepth / _channelDepth);
  737. // 判断是否为彩色图像
  738. string pixelFormatStr = _pixelFormatString.ToString().ToUpper();
  739. _isColor = pixelFormatStr.Contains("RGB") ||
  740. pixelFormatStr.Contains("BGR") ||
  741. pixelFormatStr.Contains("YUV") ||
  742. (_channels >= 3);
  743. // 检查是否为Bayer格式
  744. if (pixelFormatStr.Contains("BAYER"))
  745. {
  746. if (pixelFormatStr.Contains("BGGR"))
  747. _bayerPattern = 1;
  748. else if (pixelFormatStr.Contains("RGGB"))
  749. _bayerPattern = 2;
  750. else if (pixelFormatStr.Contains("GBRG"))
  751. _bayerPattern = 3;
  752. else if (pixelFormatStr.Contains("GRBG"))
  753. _bayerPattern = 4;
  754. _isColor = true; // Bayer格式最终会转换为彩色
  755. }
  756. LogHelper.WriteLogInfo($"图像格式: {_pixelFormatString}, 像素深度={_pixelDepth}, 通道数={_channels}, 彩色={_isColor}");
  757. return true;
  758. }
  759. catch (Exception ex)
  760. {
  761. LogHelper.WriteLogError("获取图像格式信息失败", ex);
  762. return false;
  763. }
  764. }
  765. /// <summary>
  766. /// 将原始缓冲区数据转换为ICogImage
  767. /// </summary>
  768. private ICogImage ConvertBufferToCogImage(IntPtr buffer)
  769. {
  770. if (buffer == IntPtr.Zero || _imageWidth <= 0 || _imageHeight <= 0)
  771. {
  772. return null;
  773. }
  774. try
  775. {
  776. int width = (int)_imageWidth;
  777. int height = (int)_imageHeight;
  778. ICogImage tempImage = null;
  779. // 处理Bayer格式
  780. IntPtr convertedBuffer = buffer;
  781. bool needFree = false;
  782. if (_bayerPattern != 0 && _pixelDepth == 8)
  783. {
  784. int rgbSize = width * height * 3;
  785. IntPtr rgbBuffer = Marshal.AllocHGlobal(rgbSize);
  786. if (IKDevice.Bayer2RGB(buffer, _pixelFormat, ref rgbBuffer,
  787. IKapC.ITKBUFFER_VAL_FORMAT_BGR888, width, height, _bayerPattern))
  788. {
  789. convertedBuffer = rgbBuffer;
  790. needFree = true;
  791. _isColor = true;
  792. _pixelDepth = 24;
  793. }
  794. else
  795. {
  796. Marshal.FreeHGlobal(rgbBuffer);
  797. return null;
  798. }
  799. }
  800. // 创建临时图像(可能只是引用数据)
  801. if (_isColor || _channels >= 3)
  802. {
  803. if (_pixelDepth == 24 || _pixelDepth == 8 * 3)
  804. {
  805. tempImage = CreateColorImage(convertedBuffer, width, height);
  806. }
  807. }
  808. else
  809. {
  810. if (_pixelDepth == 8)
  811. {
  812. tempImage = CreateGreyImage(convertedBuffer, width, height);
  813. }
  814. else if (_pixelDepth == 16)
  815. {
  816. tempImage = CreateGreyImage16(convertedBuffer, width, height);
  817. }
  818. }
  819. if (tempImage == null)
  820. {
  821. return null;
  822. }
  823. // ✅ 关键:强制创建独立副本
  824. ICogImage result = null;
  825. // 方法1:使用 CopyBase 创建可独立管理的副本
  826. if (tempImage is CogImage8Grey grey8Image)
  827. {
  828. result = grey8Image.CopyBase(CogImageCopyModeConstants.CopyPixels);
  829. }
  830. else if (tempImage is CogImage16Grey grey16Image)
  831. {
  832. result = grey16Image.CopyBase(CogImageCopyModeConstants.CopyPixels);
  833. }
  834. else if (tempImage is CogImage24PlanarColor colorImage)
  835. {
  836. result = colorImage.CopyBase(CogImageCopyModeConstants.CopyPixels);
  837. }
  838. else
  839. {
  840. // 方法2:转换为 Bitmap 再转回(最稳妥)
  841. using (Bitmap bitmap = tempImage.ToBitmap())
  842. {
  843. if (_isColor)
  844. {
  845. result = new CogImage24PlanarColor(bitmap);
  846. }
  847. else
  848. {
  849. result = new CogImage8Grey(bitmap);
  850. }
  851. }
  852. }
  853. // 释放临时图像(如果它是独立的对象)
  854. //if (tempImage != null && tempImage != result)
  855. //{
  856. // Marshal.ReleaseComObject(tempImage);
  857. //}
  858. //// ✅ 只有在确保图像数据已经被复制后,才能释放临时缓冲区
  859. //if (needFree && convertedBuffer != IntPtr.Zero)
  860. //{
  861. // Marshal.FreeHGlobal(convertedBuffer);
  862. //}
  863. return result;
  864. }
  865. catch (Exception ex)
  866. {
  867. LogHelper.WriteLogError("转换图像数据失败", ex);
  868. return null;
  869. }
  870. }
  871. /// <summary>
  872. /// 创建8位灰度图像
  873. /// </summary>
  874. private ICogImage CreateGreyImage(IntPtr buffer, int width, int height)
  875. {
  876. try
  877. {
  878. CogImage8Root greyRoot = new CogImage8Root();
  879. greyRoot.Initialize(width, height, buffer, width, null);
  880. CogImage8Grey greyImage = new CogImage8Grey();
  881. greyImage.SetRoot(greyRoot);
  882. return greyImage;
  883. }
  884. catch (Exception ex)
  885. {
  886. LogHelper.WriteLogError("创建8位灰度图像失败", ex);
  887. return null;
  888. }
  889. }
  890. /// <summary>
  891. /// 创建16位灰度图像
  892. /// </summary>
  893. private ICogImage CreateGreyImage16(IntPtr buffer, int width, int height)
  894. {
  895. try
  896. {
  897. // 使用CogImage16Grey(如果VisionPro支持)
  898. // 如果不支持,可以转换为8位
  899. CogImage16Root grey16Root = new CogImage16Root();
  900. grey16Root.Initialize(width, height, buffer, width * 2, null);
  901. CogImage16Grey grey16Image = new CogImage16Grey();
  902. grey16Image.SetRoot(grey16Root);
  903. return grey16Image;
  904. }
  905. catch
  906. {
  907. // 如果不支持16位,转换为8位
  908. int size = width * height;
  909. byte[] grey8Data = new byte[size];
  910. unsafe
  911. {
  912. ushort* src = (ushort*)buffer.ToPointer();
  913. for (int i = 0; i < size; i++)
  914. {
  915. grey8Data[i] = (byte)(src[i] >> 8);
  916. }
  917. }
  918. IntPtr grey8Buffer = Marshal.AllocHGlobal(size);
  919. Marshal.Copy(grey8Data, 0, grey8Buffer, size);
  920. CogImage8Root grey8Root = new CogImage8Root();
  921. grey8Root.Initialize(width, height, grey8Buffer, width, null);
  922. CogImage8Grey grey8Image = new CogImage8Grey();
  923. grey8Image.SetRoot(grey8Root);
  924. Marshal.FreeHGlobal(grey8Buffer);
  925. return grey8Image;
  926. }
  927. }
  928. /// <summary>
  929. /// 创建24位彩色图像(RGB/BGR)
  930. /// </summary>
  931. private ICogImage CreateColorImage(IntPtr buffer, int width, int height)
  932. {
  933. try
  934. {
  935. unsafe
  936. {
  937. byte* pixelData = (byte*)buffer.ToPointer();
  938. byte[] redPlane = new byte[width * height];
  939. byte[] greenPlane = new byte[width * height];
  940. byte[] bluePlane = new byte[width * height];
  941. // 假设是BGR格式(大多数相机使用BGR)
  942. for (int i = 0; i < width * height; i++)
  943. {
  944. bluePlane[i] = pixelData[3 * i];
  945. greenPlane[i] = pixelData[3 * i + 1];
  946. redPlane[i] = pixelData[3 * i + 2];
  947. }
  948. // 分配非托管内存
  949. IntPtr redPtr = Marshal.AllocHGlobal(redPlane.Length);
  950. IntPtr greenPtr = Marshal.AllocHGlobal(greenPlane.Length);
  951. IntPtr bluePtr = Marshal.AllocHGlobal(bluePlane.Length);
  952. Marshal.Copy(redPlane, 0, redPtr, redPlane.Length);
  953. Marshal.Copy(greenPlane, 0, greenPtr, greenPlane.Length);
  954. Marshal.Copy(bluePlane, 0, bluePtr, bluePlane.Length);
  955. CogImage8Root redRoot = new CogImage8Root();
  956. CogImage8Root greenRoot = new CogImage8Root();
  957. CogImage8Root blueRoot = new CogImage8Root();
  958. redRoot.Initialize(width, height, redPtr, width, null);
  959. greenRoot.Initialize(width, height, greenPtr, width, null);
  960. blueRoot.Initialize(width, height, bluePtr, width, null);
  961. CogImage24PlanarColor image = new CogImage24PlanarColor();
  962. image.SetRoots(redRoot, greenRoot, blueRoot);
  963. // 注意:这里分配的内存需要在图像使用完毕后释放
  964. // 但由于CogImage可能持有引用,需要妥善处理
  965. // 简单起见,先不释放,在实际使用中需要管理生命周期
  966. return image;
  967. }
  968. }
  969. catch (Exception ex)
  970. {
  971. LogHelper.WriteLogError("创建彩色图像失败", ex);
  972. return null;
  973. }
  974. }
  975. #endregion
  976. #region INotifyPropertyChanged
  977. public event PropertyChangedEventHandler PropertyChanged;
  978. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  979. {
  980. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  981. storage = value;
  982. RaisePropertyChanged(propertyName);
  983. return true;
  984. }
  985. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  986. {
  987. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  988. }
  989. #endregion
  990. }
  991. }