OptCamera.cs 35 KB

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