OptCamera.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. using Cognex.VisionPro;
  2. using Microsoft.Win32;
  3. using NPOI.SS.Formula.Eval;
  4. using SciCamera.Net;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Runtime.CompilerServices;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using TeamAAS_VP.Enums;
  18. using TeamAAS_VP.Interfaces;
  19. using TeamAAS_VP.Models;
  20. namespace TeamAAS_VP.Core.Cameras
  21. {
  22. public class OptCamera : ICamera, INotifyPropertyChanged
  23. {
  24. #region 字段
  25. private Thread m_hReceiveThread;
  26. // 用于序列化对同一相机实例的操作,防止同一实例被并发操作
  27. //private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
  28. // 用于保护状态变量(例如 IsGrabbing)的并发访问
  29. private readonly object _stateLock = new object();
  30. #endregion
  31. #region 属性
  32. public CameraBrand CameraBrand { get => CameraBrand.Opt; }
  33. public string Name { get; private set; }
  34. public Guid ID { get; private set; }
  35. public int Index { get; set; }
  36. public string ManufacturerName { get; private set; }
  37. public bool IsFindByIp { get; private set; }
  38. public string ModelName { get; private set; }
  39. public string SerialNumber { get; private set; }
  40. public string CameraIp { get; private set; }
  41. public CameraType CameraType { get; private set; }
  42. SciCam mvCameraAcq;
  43. public SciCam.SCI_DEVICE_INFO CameraInfo { get; private set; }
  44. public UInt32 ImageWidth { get; private set; }
  45. public UInt32 ImageHeight { get; private set; }
  46. public SciCam.SciCamPixelType PixelType { get; private set; }
  47. private bool _IsGrabbing;
  48. /// <summary>
  49. /// 正在采集
  50. /// </summary>
  51. public bool IsGrabbing
  52. {
  53. get { return _IsGrabbing; }
  54. private set { SetProperty(ref _IsGrabbing, value); }
  55. }
  56. private ICogImage _Image;
  57. public ICogImage Image
  58. {
  59. get { return _Image; }
  60. private set { SetProperty(ref _Image, value); }
  61. }
  62. public bool IsConnected { get; private set; }
  63. private bool IsHaveCamera = false;
  64. /// <summary>
  65. /// 采集用时
  66. /// </summary>
  67. public TimeSpan TotalTime { get; private set; }
  68. /// <summary>
  69. /// 错误信息
  70. /// </summary>
  71. public string ErrorMessage { get; private set; }
  72. #endregion
  73. #region 事件
  74. public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
  75. public event Action<Guid, bool> CameraConnectChangedEvent;
  76. #endregion
  77. public OptCamera(Guid id, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
  78. {
  79. ID = id;
  80. Name = serialNumber;
  81. Index = index;
  82. CameraIp = cameraip;
  83. SerialNumber = serialNumber;
  84. IsFindByIp = isFindByIp;
  85. mvCameraAcq = new SciCam();
  86. SciCam.SCI_DEVICE_INFO_LIST stDeviceList = new SciCam.SCI_DEVICE_INFO_LIST(); //设备列表
  87. uint nReVal = SciCam.DiscoveryDevices(ref stDeviceList, (uint)(SciCam.SciCamTLType.SciCam_TLType_Gige));
  88. if (nReVal != SciCam.SCI_CAMERA_OK)
  89. {
  90. return;
  91. }
  92. for (int i = 0; i < stDeviceList.count; i++)
  93. {
  94. SciCam.SCI_DEVICE_INFO device = stDeviceList.pDevInfo[i];
  95. SciCam.SciCamTLType devTlType = device.tlType;
  96. if (devTlType == SciCam.SciCamTLType.SciCam_TLType_Gige)
  97. {
  98. SciCam.SCI_DEVICE_GIGE_INFO gigeDevInfo = (SciCam.SCI_DEVICE_GIGE_INFO)SciCam.ByteToStruct(device.info.gigeInfo, typeof(SciCam.SCI_DEVICE_GIGE_INFO));
  99. uint ip1 = gigeDevInfo.ip;
  100. int nIp1 = (int)(ip1 & 0x000000ff);
  101. int nIp2 = (int)((ip1 & 0x0000ff00) >> 8);
  102. int nIp3 = (int)((ip1 & 0x00ff0000) >> 16);
  103. int nIp4 = (int)((ip1 & 0xff000000) >> 24);
  104. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  105. if (IsFindByIp)
  106. {
  107. if (CameraIp == ip)
  108. {
  109. ManufacturerName = gigeDevInfo.manufactureName;
  110. ModelName = gigeDevInfo.modelName;
  111. SerialNumber = gigeDevInfo.serialNumber;
  112. CameraType = CameraType.GIGE;
  113. CameraInfo = device;
  114. IsHaveCamera = true;
  115. break;
  116. }
  117. }
  118. else
  119. {
  120. if (string.Equals(gigeDevInfo.serialNumber, serialNumber))
  121. {
  122. ManufacturerName = gigeDevInfo.manufactureName;
  123. ModelName = gigeDevInfo.modelName;
  124. SerialNumber = gigeDevInfo.serialNumber;
  125. CameraType = CameraType.GIGE;
  126. CameraInfo = device;
  127. IsHaveCamera = true;
  128. break;
  129. }
  130. }
  131. }
  132. }
  133. IsConnected = false;
  134. }
  135. #region 方法
  136. /// <summary>
  137. /// 获取设备
  138. /// </summary>
  139. /// <returns></returns>
  140. public static CameraInfo[] GetDevices()
  141. {
  142. List<CameraInfo> cameras = new List<CameraInfo>();
  143. try
  144. {
  145. if (!CheckSoftwareInstalled().isInstalled)
  146. {
  147. LogHelper.WriteLogInfo("未安装OPT");
  148. return cameras.ToArray();
  149. }
  150. SciCam.SCI_DEVICE_INFO_LIST stDeviceList = new SciCam.SCI_DEVICE_INFO_LIST(); //设备列表
  151. uint nReVal = SciCam.DiscoveryDevices(ref stDeviceList, (uint)(SciCam.SciCamTLType.SciCam_TLType_Gige));
  152. if (nReVal != SciCam.SCI_CAMERA_OK)
  153. {
  154. return cameras.ToArray();
  155. }
  156. for (int i = 0; i < stDeviceList.count; i++)
  157. {
  158. SciCam.SCI_DEVICE_INFO device = stDeviceList.pDevInfo[i];
  159. SciCam.SciCamTLType devTlType = device.tlType;
  160. if (devTlType == SciCam.SciCamTLType.SciCam_TLType_Gige)
  161. {
  162. SciCam.SCI_DEVICE_GIGE_INFO gigeDevInfo = (SciCam.SCI_DEVICE_GIGE_INFO)SciCam.ByteToStruct(device.info.gigeInfo, typeof(SciCam.SCI_DEVICE_GIGE_INFO));
  163. uint ip1 = gigeDevInfo.ip;
  164. int nIp1 = (int)(ip1 & 0x000000ff);
  165. int nIp2 = (int)((ip1 & 0x0000ff00) >> 8);
  166. int nIp3 = (int)((ip1 & 0x00ff0000) >> 16);
  167. int nIp4 = (int)((ip1 & 0xff000000) >> 24);
  168. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  169. cameras.Add(new CameraInfo()
  170. {
  171. CameraNo = i + 1,
  172. CameraName = gigeDevInfo.name,
  173. CameraBrand = CameraBrand.Opt,
  174. CameraType = CameraType.GIGE,
  175. ManufacturerName = gigeDevInfo.manufactureName,
  176. Model = gigeDevInfo.modelName,
  177. SerialNumber = gigeDevInfo.serialNumber,
  178. CameraIp = ip,
  179. IsFindByIp = true,
  180. });
  181. }
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. LogHelper.WriteLogError("搜索OPT相机列表时出错!", ex);
  187. }
  188. return cameras.ToArray();
  189. }
  190. /// <summary>
  191. /// 检查相机软件是否安装
  192. /// </summary>
  193. /// <returns></returns>
  194. public static (bool isInstalled, string version) CheckSoftwareInstalled()
  195. {
  196. //string softwareName = "OPT Camera Viewer";
  197. //string softwareVersion = "4.0.0.3";
  198. //string[] registryPaths = new[]
  199. //{
  200. // @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  201. // @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
  202. //};
  203. //foreach (var path in registryPaths)
  204. //{
  205. // using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
  206. // {
  207. // if (key == null) continue;
  208. // foreach (string subKeyName in key.GetSubKeyNames())
  209. // {
  210. // using (RegistryKey subKey = key.OpenSubKey(subKeyName))
  211. // {
  212. // string displayName = subKey.GetValue("DisplayName")?.ToString();
  213. // if (displayName != null && displayName.ToUpper().Trim() == softwareName.ToUpper())
  214. // {
  215. // string version = subKey.GetValue("DisplayVersion")?.ToString();
  216. // Version v1 = new Version(version);
  217. // Version v2 = new Version(softwareVersion);
  218. // if (v1 >= v2)
  219. // {
  220. // return (true, version);
  221. // }
  222. // else
  223. // {
  224. // return (false, version);
  225. // }
  226. // }
  227. // }
  228. // }
  229. // }
  230. //}
  231. //return (false, "");
  232. return (true, "4.0.0.3"); // TODO: Opt相机不检查软件安装
  233. }
  234. /// <summary>
  235. /// 打开相机
  236. /// </summary>
  237. /// <returns></returns>
  238. /// <exception cref="Exception"></exception>
  239. public bool OpenDevice()
  240. {
  241. //_operationSemaphore.Wait();
  242. uint nReVal = SciCam.SCI_CAMERA_OK;
  243. try
  244. {
  245. if (!IsHaveCamera)
  246. {
  247. mvCameraAcq = new SciCam();
  248. SciCam.SCI_DEVICE_INFO_LIST stDeviceList = new SciCam.SCI_DEVICE_INFO_LIST(); //设备列表
  249. nReVal = SciCam.DiscoveryDevices(ref stDeviceList, (uint)(SciCam.SciCamTLType.SciCam_TLType_Gige));
  250. if (nReVal != SciCam.SCI_CAMERA_OK)
  251. {
  252. return false;
  253. }
  254. for (int i = 0; i < stDeviceList.count; i++)
  255. {
  256. SciCam.SCI_DEVICE_INFO device = stDeviceList.pDevInfo[i];
  257. SciCam.SciCamTLType devTlType = device.tlType;
  258. if (devTlType == SciCam.SciCamTLType.SciCam_TLType_Gige)
  259. {
  260. SciCam.SCI_DEVICE_GIGE_INFO gigeDevInfo = (SciCam.SCI_DEVICE_GIGE_INFO)SciCam.ByteToStruct(device.info.gigeInfo, typeof(SciCam.SCI_DEVICE_GIGE_INFO));
  261. uint ip1 = gigeDevInfo.ip;
  262. int nIp1 = (int)(ip1 & 0x000000ff);
  263. int nIp2 = (int)((ip1 & 0x0000ff00) >> 8);
  264. int nIp3 = (int)((ip1 & 0x00ff0000) >> 16);
  265. int nIp4 = (int)((ip1 & 0xff000000) >> 24);
  266. string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
  267. if (IsFindByIp)
  268. {
  269. if (CameraIp == ip)
  270. {
  271. ManufacturerName = gigeDevInfo.manufactureName;
  272. ModelName = gigeDevInfo.modelName;
  273. SerialNumber = gigeDevInfo.serialNumber;
  274. CameraType = CameraType.GIGE;
  275. CameraInfo = device;
  276. IsHaveCamera = true;
  277. break;
  278. }
  279. }
  280. else
  281. {
  282. if (string.Equals(gigeDevInfo.serialNumber, SerialNumber))
  283. {
  284. ManufacturerName = gigeDevInfo.manufactureName;
  285. ModelName = gigeDevInfo.modelName;
  286. SerialNumber = gigeDevInfo.serialNumber;
  287. CameraType = CameraType.GIGE;
  288. CameraInfo = device;
  289. IsHaveCamera = true;
  290. break;
  291. }
  292. }
  293. }
  294. }
  295. if (!IsHaveCamera)
  296. {
  297. throw new Exception("没有发现相机");
  298. }
  299. }
  300. SciCam.SCI_DEVICE_INFO sCI_DEVICE_INFO= CameraInfo;
  301. nReVal = mvCameraAcq.CreateDevice(ref sCI_DEVICE_INFO);
  302. if (nReVal != SciCam.SCI_CAMERA_OK)
  303. {
  304. Console.WriteLine("Creat Device Fail! nRet:{0}", nReVal);
  305. throw new Exception("Creat Device Fail!");
  306. }
  307. // ch:打开设备 | en:Open device
  308. nReVal = mvCameraAcq.OpenDevice();
  309. // ch:设置触发模式为off | en:Set trigger mode as off
  310. nReVal = mvCameraAcq.SetEnumValueByStringEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerMode", "Off");
  311. if (!IsConnected)
  312. {
  313. CameraConnectChangedEvent?.Invoke(ID, true);
  314. }
  315. mvCameraAcq.SetGrabTimeout(300);
  316. IsConnected = mvCameraAcq.IsDeviceOpen();
  317. if (IsConnected)
  318. {
  319. mvCameraAcq.StartGrabbing();
  320. }
  321. return IsConnected;
  322. }
  323. finally
  324. {
  325. //_operationSemaphore.Release();
  326. }
  327. }
  328. /// <summary>
  329. /// 打开相机异步
  330. /// </summary>
  331. /// <returns></returns>
  332. public Task<bool> OpenDeviceAsync()
  333. {
  334. return Task.Run(() =>
  335. {
  336. return OpenDevice();
  337. });
  338. }
  339. /// <summary>
  340. /// 关闭相机
  341. /// </summary>
  342. public void CloseDevice()
  343. {
  344. // ch:关闭设备 | en:Close Device
  345. //_operationSemaphore.Wait();
  346. try
  347. {
  348. mvCameraAcq.StopGrabbing();
  349. mvCameraAcq.CloseDevice();
  350. }
  351. finally
  352. {
  353. //_operationSemaphore.Release();
  354. }
  355. }
  356. /// <summary>
  357. /// 采集图像
  358. /// </summary>
  359. /// <returns></returns>
  360. public ICogImage Grab()
  361. {
  362. //_operationSemaphore.Wait();
  363. uint nReVal = SciCam.SCI_CAMERA_OK;
  364. IntPtr payload = IntPtr.Zero;
  365. try
  366. {
  367. Stopwatch sw = Stopwatch.StartNew();
  368. for (int i = 0; i < 5; i++)
  369. {
  370. try
  371. {
  372. if (!mvCameraAcq.IsDeviceOpen())
  373. {
  374. OpenDevice();
  375. }
  376. //if (!mvCameraAcq.IsGrabbing())
  377. //{
  378. // mvCameraAcq.StartGrabbing();
  379. //}
  380. //nReVal = mvCameraAcq.StartGrabbing();
  381. mvCameraAcq.ClearPayloadBuffer();
  382. nReVal = mvCameraAcq.Grab(ref payload);
  383. if (nReVal == SciCam.SCI_CAMERA_OK)
  384. {
  385. Image = GetConvertedInfo(payload);
  386. mvCameraAcq.FreePayload(payload);
  387. //nReVal = mvCameraAcq.StopGrabbing();
  388. TotalTime = sw.Elapsed;
  389. ErrorMessage= $"{i+1}";
  390. return Image;
  391. }
  392. else
  393. {
  394. nReVal = mvCameraAcq.FreePayload(payload);
  395. //nReVal = mvCameraAcq.StopGrabbing();
  396. //_operationSemaphore.Release();
  397. CloseDevice();
  398. OpenDevice();
  399. ErrorMessage = "图像采集失败!";
  400. }
  401. }
  402. catch (Exception ex)
  403. {
  404. //_operationSemaphore.Release();
  405. CloseDevice();
  406. OpenDevice();
  407. ErrorMessage = ex.Message;
  408. }
  409. }
  410. if (IsConnected)
  411. {
  412. IsConnected = false;
  413. CameraConnectChangedEvent?.Invoke(ID, false);
  414. }
  415. return null;
  416. }
  417. finally
  418. {
  419. //_operationSemaphore.Release();
  420. }
  421. }
  422. /// <summary>
  423. /// 开始采集图像
  424. /// </summary>
  425. public void StartGrabbing()
  426. {
  427. lock (_stateLock)
  428. {
  429. if (IsGrabbing)
  430. return;
  431. IsGrabbing = true;
  432. }
  433. m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
  434. m_hReceiveThread.Start();
  435. }
  436. /// <summary>
  437. /// 停止采集图像
  438. /// </summary>
  439. public void StopGrabbing()
  440. {
  441. try
  442. {
  443. lock (_stateLock)
  444. {
  445. IsGrabbing = false;
  446. }
  447. if (m_hReceiveThread != null)
  448. {
  449. m_hReceiveThread.Abort();
  450. m_hReceiveThread = null;
  451. }
  452. }
  453. catch (Exception)
  454. {
  455. }
  456. }
  457. /// <summary>
  458. /// 设置曝光时间
  459. /// </summary>
  460. /// <param name="ExposureTime"></param>
  461. /// <returns></returns>
  462. public bool SetExposureTime(float ExposureTime)
  463. {
  464. //_operationSemaphore.Wait();
  465. try
  466. {
  467. if (!mvCameraAcq.IsDeviceOpen())
  468. return false;
  469. uint nReVal = SciCam.SCI_CAMERA_OK;
  470. nReVal = mvCameraAcq.SetIntValue("ExposureTime", (int)ExposureTime);
  471. if (nReVal != SciCam.SCI_CAMERA_OK)
  472. {
  473. mvCameraAcq.SetFloatValue("ExposureTime", ExposureTime);
  474. }
  475. return true;
  476. }
  477. finally
  478. {
  479. //_operationSemaphore.Release();
  480. }
  481. }
  482. /// <summary>
  483. /// 获取曝光时间
  484. /// </summary>
  485. /// <returns></returns>
  486. public float GetExposureTime()
  487. {
  488. //_operationSemaphore.Wait();
  489. try
  490. {
  491. if (!mvCameraAcq.IsDeviceOpen())
  492. return 0;
  493. uint nReVal = SciCam.SCI_CAMERA_OK;
  494. SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
  495. nReVal = mvCameraAcq.GetIntValue("ExposureTime", ref iNodeVal);
  496. if (nReVal != SciCam.SCI_CAMERA_OK)
  497. {
  498. SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
  499. nReVal = mvCameraAcq.GetFloatValue("ExposureTime", ref fNodeVal);
  500. if (nReVal == SciCam.SCI_CAMERA_OK)
  501. {
  502. return (float)fNodeVal.dVal;
  503. }
  504. else
  505. {
  506. return 0;
  507. }
  508. }
  509. else
  510. {
  511. return (float)iNodeVal.nVal;
  512. }
  513. }
  514. finally
  515. {
  516. //_operationSemaphore.Release();
  517. }
  518. }
  519. /// <summary>
  520. /// 设置增益
  521. /// </summary>
  522. /// <param name="Gain"></param>
  523. /// <returns></returns>
  524. public bool SetGain(float Gain)
  525. {
  526. //_operationSemaphore.Wait();
  527. try
  528. {
  529. if (!mvCameraAcq.IsDeviceOpen())
  530. return false;
  531. uint nReVal = SciCam.SCI_CAMERA_OK;
  532. nReVal = mvCameraAcq.SetIntValue("Gain", (int)Gain);
  533. if (nReVal != SciCam.SCI_CAMERA_OK)
  534. {
  535. mvCameraAcq.SetFloatValue("Gain", Gain);
  536. }
  537. return true;
  538. }
  539. finally
  540. {
  541. //_operationSemaphore.Release();
  542. }
  543. }
  544. /// <summary>
  545. /// 获取增益
  546. /// </summary>
  547. /// <returns></returns>
  548. public float GetGain()
  549. {
  550. //_operationSemaphore.Wait();
  551. try
  552. {
  553. if (!mvCameraAcq.IsDeviceOpen())
  554. return 0;
  555. uint nReVal = SciCam.SCI_CAMERA_OK;
  556. SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
  557. nReVal = mvCameraAcq.GetIntValue("Gain", ref iNodeVal);
  558. if (nReVal != SciCam.SCI_CAMERA_OK)
  559. {
  560. SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
  561. nReVal = mvCameraAcq.GetFloatValue("Gain", ref fNodeVal);
  562. if (nReVal == SciCam.SCI_CAMERA_OK)
  563. {
  564. return (float)fNodeVal.dVal;
  565. }
  566. else
  567. {
  568. return 0;
  569. }
  570. }
  571. else
  572. {
  573. return (float)iNodeVal.nVal;
  574. }
  575. }
  576. finally
  577. {
  578. //_operationSemaphore.Release();
  579. }
  580. }
  581. private void GetStreamThreadProc()
  582. {
  583. while (IsGrabbing)
  584. {
  585. try
  586. {
  587. Grab();
  588. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
  589. }
  590. catch (Exception)
  591. {
  592. }
  593. Thread.Sleep(10);
  594. }
  595. IsGrabbing = false;
  596. }
  597. private ICogImage GetConvertedInfo(IntPtr payload)
  598. {
  599. if (payload == IntPtr.Zero)
  600. {
  601. return null;
  602. }
  603. SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE payloadAttribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
  604. uint nReVal = SciCam.PayloadGetAttribute(payload, ref payloadAttribute);
  605. if (nReVal != SciCam.SCI_CAMERA_OK)
  606. {
  607. return null;
  608. }
  609. bool imgIsComplete = payloadAttribute.isComplete;
  610. SciCam.SciCamPayloadMode payloadMode = payloadAttribute.payloadMode;
  611. SciCam.SciCamPixelType imgPixelType = payloadAttribute.imgAttr.pixelType;
  612. ulong imgWidth = payloadAttribute.imgAttr.width;
  613. ulong imgHeight = payloadAttribute.imgAttr.height;
  614. ulong framID = payloadAttribute.frameID;
  615. if (!imgIsComplete || payloadMode != SciCam.SciCamPayloadMode.SciCam_PayloadMode_2D)
  616. {
  617. return null;
  618. }
  619. IntPtr imgData = IntPtr.Zero;
  620. nReVal = SciCam.PayloadGetImage(payload, ref imgData);
  621. if (nReVal != SciCam.SCI_CAMERA_OK)
  622. {
  623. return null;
  624. }
  625. long destImgSize = 0;
  626. if (imgPixelType == SciCam.SciCamPixelType.Mono1p ||
  627. imgPixelType == SciCam.SciCamPixelType.Mono2p ||
  628. imgPixelType == SciCam.SciCamPixelType.Mono4p ||
  629. imgPixelType == SciCam.SciCamPixelType.Mono8s ||
  630. imgPixelType == SciCam.SciCamPixelType.Mono8 ||
  631. imgPixelType == SciCam.SciCamPixelType.Mono10 ||
  632. imgPixelType == SciCam.SciCamPixelType.Mono10p ||
  633. imgPixelType == SciCam.SciCamPixelType.Mono12 ||
  634. imgPixelType == SciCam.SciCamPixelType.Mono12p ||
  635. imgPixelType == SciCam.SciCamPixelType.Mono14 ||
  636. imgPixelType == SciCam.SciCamPixelType.Mono16 ||
  637. imgPixelType == SciCam.SciCamPixelType.Mono10Packed ||
  638. imgPixelType == SciCam.SciCamPixelType.Mono12Packed ||
  639. imgPixelType == SciCam.SciCamPixelType.Mono14p)
  640. {
  641. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, IntPtr.Zero, ref destImgSize, true);
  642. if (nReVal == SciCam.SCI_CAMERA_OK)
  643. {
  644. IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
  645. try
  646. {
  647. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, destImg, ref destImgSize, true);
  648. if (nReVal == SciCam.SCI_CAMERA_OK)
  649. {
  650. byte[] bBitmap = new byte[destImgSize];
  651. Marshal.Copy(destImg, bBitmap, 0, (int)destImgSize);
  652. Bitmap bitMap = new Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
  653. System.Drawing.Imaging.BitmapData bitmapData = bitMap.LockBits(new Rectangle(0, 0, (int)imgWidth, (int)imgHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
  654. Marshal.Copy(bBitmap, 0, bitmapData.Scan0, (int)destImgSize);
  655. bitMap.UnlockBits(bitmapData);
  656. //设置调色板
  657. System.Drawing.Imaging.ColorPalette palette = bitMap.Palette;
  658. for (int i = 0; i < 256; i++)
  659. {
  660. palette.Entries[i] = Color.FromArgb(i, i, i);
  661. }
  662. bitMap.Palette = palette;
  663. //显示图片
  664. return TransformICogImage((uint)imgHeight, (uint)imgWidth, destImg, SciCam.SciCamPixelType.Mono8);
  665. }
  666. }
  667. catch (Exception ex)
  668. {
  669. }
  670. finally
  671. {
  672. Marshal.FreeHGlobal(destImg);
  673. }
  674. }
  675. }
  676. else
  677. {
  678. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, IntPtr.Zero, ref destImgSize, true);
  679. if (nReVal == SciCam.SCI_CAMERA_OK)
  680. {
  681. IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
  682. try
  683. {
  684. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, destImg, ref destImgSize, true);
  685. if (nReVal == SciCam.SCI_CAMERA_OK)
  686. {
  687. IntPtr pTemp = IntPtr.Zero;
  688. Byte[] byteArrImageData = new Byte[imgWidth * imgHeight * 3];
  689. unsafe
  690. {
  691. byte* pBufForSaveImage = (byte*)destImg;
  692. UInt32 nSupWidth = ((UInt32)imgWidth + (UInt32)3) & 0xfffffffc;
  693. for (int nRow = 0; nRow < (int)imgHeight; nRow++)
  694. {
  695. for (int col = 0; col < (int)imgWidth; col++)
  696. {
  697. byteArrImageData[nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col)];
  698. byteArrImageData[(int)imgWidth * (int)imgHeight + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 1)];
  699. byteArrImageData[(int)imgWidth * (int)imgHeight * 2 + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 2)];
  700. }
  701. }
  702. pTemp = Marshal.UnsafeAddrOfPinnedArrayElement(byteArrImageData, 0);
  703. }
  704. //显示图片
  705. return TransformICogImage((uint)imgHeight, (uint)imgWidth, pTemp, SciCam.SciCamPixelType.RGB8);
  706. }
  707. }
  708. catch (Exception ex)
  709. {
  710. }
  711. finally
  712. {
  713. Marshal.FreeHGlobal(destImg);
  714. }
  715. }
  716. }
  717. return null;
  718. }
  719. private ICogImage TransformICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, SciCam.SciCamPixelType enPixelType)
  720. {
  721. try
  722. {
  723. ICogImage image;
  724. if (enPixelType == SciCam.SciCamPixelType.Mono8)
  725. {
  726. CogImage8Root cogImage8Root = new CogImage8Root();
  727. cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
  728. CogImage8Grey cogImage8Grey = new CogImage8Grey();
  729. cogImage8Grey.SetRoot(cogImage8Root);
  730. image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
  731. System.GC.Collect();
  732. return image;
  733. }
  734. else
  735. {
  736. CogImage8Root image0 = new CogImage8Root();
  737. IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
  738. image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
  739. CogImage8Root image1 = new CogImage8Root();
  740. IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight);
  741. image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
  742. CogImage8Root image2 = new CogImage8Root();
  743. IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight * 2);
  744. image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
  745. CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
  746. //colorImage.SetRoots(image0, image1, image2);
  747. colorImage.SetRoots(image2, image1, image0);
  748. image = colorImage.ScaleImage((int)nWidth, (int)nHeight);
  749. System.GC.Collect();
  750. return image;
  751. }
  752. }
  753. catch (System.Exception)
  754. {
  755. return null;
  756. }
  757. }
  758. #endregion
  759. #region 属性通知
  760. /// <summary>
  761. /// Occurs when a property value changes.
  762. /// </summary>
  763. public event PropertyChangedEventHandler PropertyChanged;
  764. /// <summary>
  765. /// Checks if a property already matches a desired value. Sets the property and
  766. /// notifies listeners only when necessary.
  767. /// </summary>
  768. /// <typeparam name="T">Type of the property.</typeparam>
  769. /// <param name="storage">Reference to a property with both getter and setter.</param>
  770. /// <param name="value">Desired value for the property.</param>
  771. /// <param name="propertyName">Name of the property used to notify listeners. This
  772. /// value is optional and can be provided automatically when invoked from compilers that
  773. /// support CallerMemberName.</param>
  774. /// <returns>True if the value was changed, false if the existing value matched the
  775. /// desired value.</returns>
  776. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  777. {
  778. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  779. storage = value;
  780. RaisePropertyChanged(propertyName);
  781. return true;
  782. }
  783. /// <summary>
  784. /// Checks if a property already matches a desired value. Sets the property and
  785. /// notifies listeners only when necessary.
  786. /// </summary>
  787. /// <typeparam name="T">Type of the property.</typeparam>
  788. /// <param name="storage">Reference to a property with both getter and setter.</param>
  789. /// <param name="value">Desired value for the property.</param>
  790. /// <param name="propertyName">Name of the property used to notify listeners. This
  791. /// value is optional and can be provided automatically when invoked from compilers that
  792. /// support CallerMemberName.</param>
  793. /// <param name="onChanged">Action that is called after the property value has been changed.</param>
  794. /// <returns>True if the value was changed, false if the existing value matched the
  795. /// desired value.</returns>
  796. protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
  797. {
  798. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  799. storage = value;
  800. onChanged?.Invoke();
  801. RaisePropertyChanged(propertyName);
  802. return true;
  803. }
  804. /// <summary>
  805. /// Raises this object's PropertyChanged event.
  806. /// </summary>
  807. /// <param name="propertyName">Name of the property used to notify listeners. This
  808. /// value is optional and can be provided automatically when invoked from compilers
  809. /// that support <see cref="CallerMemberNameAttribute"/>.</param>
  810. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  811. {
  812. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  813. }
  814. /// <summary>
  815. /// Raises this object's PropertyChanged event.
  816. /// </summary>
  817. /// <param name="args">The PropertyChangedEventArgs</param>
  818. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
  819. {
  820. PropertyChanged?.Invoke(this, args);
  821. }
  822. #endregion
  823. }
  824. }