OptCamera.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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. /// <returns></returns>
  429. public ICogImage Grab2(bool isRealtime = true)
  430. {
  431. //_operationSemaphore.Wait();
  432. uint nReVal = SciCam.SCI_CAMERA_OK;
  433. IntPtr payload = IntPtr.Zero;
  434. try
  435. {
  436. Stopwatch sw = Stopwatch.StartNew();
  437. for (int i = 0; i < 5; i++)
  438. {
  439. try
  440. {
  441. //if (!mvCameraAcq.IsDeviceOpen())
  442. //{
  443. // OpenDevice();
  444. //}
  445. //nReVal = mvCameraAcq.StartGrabbing();
  446. mvCameraAcq.ClearPayloadBuffer();
  447. nReVal = mvCameraAcq.SetCommandValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerSoftware");
  448. nReVal = mvCameraAcq.Grab(ref payload);
  449. if (nReVal == SciCam.SCI_CAMERA_OK)
  450. {
  451. Image = GetConvertedInfo(payload);
  452. mvCameraAcq.FreePayload(payload);
  453. //nReVal = mvCameraAcq.StopGrabbing();
  454. TotalTime = sw.Elapsed;
  455. return Image;
  456. }
  457. //else
  458. //{
  459. // nReVal = mvCameraAcq.FreePayload(payload);
  460. // //nReVal = mvCameraAcq.StopGrabbing();
  461. // //_operationSemaphore.Release();
  462. // CloseDevice();
  463. // OpenDevice();
  464. // ErrorMessage = "图像采集失败!";
  465. //}
  466. }
  467. catch (Exception ex)
  468. {
  469. //_operationSemaphore.Release();
  470. CloseDevice();
  471. OpenDevice();
  472. ErrorMessage = ex.Message;
  473. }
  474. }
  475. if (IsConnected)
  476. {
  477. IsConnected = false;
  478. CameraConnectChangedEvent?.Invoke(ID, false);
  479. }
  480. return null;
  481. }
  482. finally
  483. {
  484. //_operationSemaphore.Release();
  485. }
  486. }
  487. /// <summary>
  488. /// 开始采集图像
  489. /// </summary>
  490. public void StartGrabbing()
  491. {
  492. lock (_stateLock)
  493. {
  494. if (IsGrabbing)
  495. return;
  496. IsGrabbing = true;
  497. }
  498. m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
  499. m_hReceiveThread.Start();
  500. }
  501. /// <summary>
  502. /// 停止采集图像
  503. /// </summary>
  504. public void StopGrabbing()
  505. {
  506. try
  507. {
  508. lock (_stateLock)
  509. {
  510. IsGrabbing = false;
  511. }
  512. if (m_hReceiveThread != null)
  513. {
  514. m_hReceiveThread.Abort();
  515. m_hReceiveThread = null;
  516. }
  517. }
  518. catch (Exception)
  519. {
  520. }
  521. }
  522. /// <summary>
  523. /// 设置曝光时间
  524. /// </summary>
  525. /// <param name="ExposureTime"></param>
  526. /// <returns></returns>
  527. public bool SetExposureTime(float ExposureTime)
  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("ExposureTime", (int)ExposureTime);
  536. if (nReVal != SciCam.SCI_CAMERA_OK)
  537. {
  538. mvCameraAcq.SetFloatValue("ExposureTime", ExposureTime);
  539. }
  540. return true;
  541. }
  542. finally
  543. {
  544. //_operationSemaphore.Release();
  545. }
  546. }
  547. /// <summary>
  548. /// 获取曝光时间
  549. /// </summary>
  550. /// <returns></returns>
  551. public float GetExposureTime()
  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("ExposureTime", 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("ExposureTime", 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. /// <summary>
  585. /// 设置增益
  586. /// </summary>
  587. /// <param name="Gain"></param>
  588. /// <returns></returns>
  589. public bool SetGain(float Gain)
  590. {
  591. //_operationSemaphore.Wait();
  592. try
  593. {
  594. if (!mvCameraAcq.IsDeviceOpen())
  595. return false;
  596. uint nReVal = SciCam.SCI_CAMERA_OK;
  597. nReVal = mvCameraAcq.SetIntValue("Gain", (int)Gain);
  598. if (nReVal != SciCam.SCI_CAMERA_OK)
  599. {
  600. mvCameraAcq.SetFloatValue("Gain", Gain);
  601. }
  602. return true;
  603. }
  604. finally
  605. {
  606. //_operationSemaphore.Release();
  607. }
  608. }
  609. /// <summary>
  610. /// 获取增益
  611. /// </summary>
  612. /// <returns></returns>
  613. public float GetGain()
  614. {
  615. //_operationSemaphore.Wait();
  616. try
  617. {
  618. if (!mvCameraAcq.IsDeviceOpen())
  619. return 0;
  620. uint nReVal = SciCam.SCI_CAMERA_OK;
  621. SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
  622. nReVal = mvCameraAcq.GetIntValue("Gain", ref iNodeVal);
  623. if (nReVal != SciCam.SCI_CAMERA_OK)
  624. {
  625. SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
  626. nReVal = mvCameraAcq.GetFloatValue("Gain", ref fNodeVal);
  627. if (nReVal == SciCam.SCI_CAMERA_OK)
  628. {
  629. return (float)fNodeVal.dVal;
  630. }
  631. else
  632. {
  633. return 0;
  634. }
  635. }
  636. else
  637. {
  638. return (float)iNodeVal.nVal;
  639. }
  640. }
  641. finally
  642. {
  643. //_operationSemaphore.Release();
  644. }
  645. }
  646. private void GetStreamThreadProc()
  647. {
  648. while (IsGrabbing)
  649. {
  650. try
  651. {
  652. Grab();
  653. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage,ID);
  654. }
  655. catch (Exception)
  656. {
  657. }
  658. Thread.Sleep(10);
  659. }
  660. IsGrabbing = false;
  661. }
  662. private ICogImage GetConvertedInfo(IntPtr payload)
  663. {
  664. if (payload == IntPtr.Zero)
  665. {
  666. return null;
  667. }
  668. SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE payloadAttribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
  669. uint nReVal = SciCam.PayloadGetAttribute(payload, ref payloadAttribute);
  670. if (nReVal != SciCam.SCI_CAMERA_OK)
  671. {
  672. return null;
  673. }
  674. bool imgIsComplete = payloadAttribute.isComplete;
  675. SciCam.SciCamPayloadMode payloadMode = payloadAttribute.payloadMode;
  676. SciCam.SciCamPixelType imgPixelType = payloadAttribute.imgAttr.pixelType;
  677. ulong imgWidth = payloadAttribute.imgAttr.width;
  678. ulong imgHeight = payloadAttribute.imgAttr.height;
  679. ulong framID = payloadAttribute.frameID;
  680. if (!imgIsComplete || payloadMode != SciCam.SciCamPayloadMode.SciCam_PayloadMode_2D)
  681. {
  682. return null;
  683. }
  684. IntPtr imgData = IntPtr.Zero;
  685. nReVal = SciCam.PayloadGetImage(payload, ref imgData);
  686. if (nReVal != SciCam.SCI_CAMERA_OK)
  687. {
  688. return null;
  689. }
  690. long destImgSize = 0;
  691. if (imgPixelType == SciCam.SciCamPixelType.Mono1p ||
  692. imgPixelType == SciCam.SciCamPixelType.Mono2p ||
  693. imgPixelType == SciCam.SciCamPixelType.Mono4p ||
  694. imgPixelType == SciCam.SciCamPixelType.Mono8s ||
  695. imgPixelType == SciCam.SciCamPixelType.Mono8 ||
  696. imgPixelType == SciCam.SciCamPixelType.Mono10 ||
  697. imgPixelType == SciCam.SciCamPixelType.Mono10p ||
  698. imgPixelType == SciCam.SciCamPixelType.Mono12 ||
  699. imgPixelType == SciCam.SciCamPixelType.Mono12p ||
  700. imgPixelType == SciCam.SciCamPixelType.Mono14 ||
  701. imgPixelType == SciCam.SciCamPixelType.Mono16 ||
  702. imgPixelType == SciCam.SciCamPixelType.Mono10Packed ||
  703. imgPixelType == SciCam.SciCamPixelType.Mono12Packed ||
  704. imgPixelType == SciCam.SciCamPixelType.Mono14p)
  705. {
  706. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, IntPtr.Zero, ref destImgSize, true);
  707. if (nReVal == SciCam.SCI_CAMERA_OK)
  708. {
  709. IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
  710. try
  711. {
  712. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, destImg, ref destImgSize, true);
  713. if (nReVal == SciCam.SCI_CAMERA_OK)
  714. {
  715. byte[] bBitmap = new byte[destImgSize];
  716. Marshal.Copy(destImg, bBitmap, 0, (int)destImgSize);
  717. Bitmap bitMap = new Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
  718. 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);
  719. Marshal.Copy(bBitmap, 0, bitmapData.Scan0, (int)destImgSize);
  720. bitMap.UnlockBits(bitmapData);
  721. //设置调色板
  722. System.Drawing.Imaging.ColorPalette palette = bitMap.Palette;
  723. for (int i = 0; i < 256; i++)
  724. {
  725. palette.Entries[i] = Color.FromArgb(i, i, i);
  726. }
  727. bitMap.Palette = palette;
  728. //显示图片
  729. return TransformICogImage((uint)imgHeight, (uint)imgWidth, destImg, SciCam.SciCamPixelType.Mono8);
  730. }
  731. }
  732. catch (Exception ex)
  733. {
  734. }
  735. finally
  736. {
  737. Marshal.FreeHGlobal(destImg);
  738. }
  739. }
  740. }
  741. else
  742. {
  743. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, IntPtr.Zero, ref destImgSize, true);
  744. if (nReVal == SciCam.SCI_CAMERA_OK)
  745. {
  746. IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
  747. try
  748. {
  749. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, destImg, ref destImgSize, true);
  750. if (nReVal == SciCam.SCI_CAMERA_OK)
  751. {
  752. IntPtr pTemp = IntPtr.Zero;
  753. Byte[] byteArrImageData = new Byte[imgWidth * imgHeight * 3];
  754. unsafe
  755. {
  756. byte* pBufForSaveImage = (byte*)destImg;
  757. UInt32 nSupWidth = ((UInt32)imgWidth + (UInt32)3) & 0xfffffffc;
  758. for (int nRow = 0; nRow < (int)imgHeight; nRow++)
  759. {
  760. for (int col = 0; col < (int)imgWidth; col++)
  761. {
  762. byteArrImageData[nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col)];
  763. byteArrImageData[(int)imgWidth * (int)imgHeight + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 1)];
  764. byteArrImageData[(int)imgWidth * (int)imgHeight * 2 + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 2)];
  765. }
  766. }
  767. pTemp = Marshal.UnsafeAddrOfPinnedArrayElement(byteArrImageData, 0);
  768. }
  769. //显示图片
  770. return TransformICogImage((uint)imgHeight, (uint)imgWidth, pTemp, SciCam.SciCamPixelType.RGB8);
  771. }
  772. }
  773. catch (Exception ex)
  774. {
  775. }
  776. finally
  777. {
  778. Marshal.FreeHGlobal(destImg);
  779. }
  780. }
  781. }
  782. return null;
  783. }
  784. private ICogImage TransformICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, SciCam.SciCamPixelType enPixelType)
  785. {
  786. try
  787. {
  788. ICogImage image;
  789. if (enPixelType == SciCam.SciCamPixelType.Mono8)
  790. {
  791. CogImage8Root cogImage8Root = new CogImage8Root();
  792. cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
  793. CogImage8Grey cogImage8Grey = new CogImage8Grey();
  794. cogImage8Grey.SetRoot(cogImage8Root);
  795. image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
  796. System.GC.Collect();
  797. return image;
  798. }
  799. else
  800. {
  801. CogImage8Root image0 = new CogImage8Root();
  802. IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
  803. image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
  804. CogImage8Root image1 = new CogImage8Root();
  805. IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight);
  806. image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
  807. CogImage8Root image2 = new CogImage8Root();
  808. IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight * 2);
  809. image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
  810. CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
  811. //colorImage.SetRoots(image0, image1, image2);
  812. colorImage.SetRoots(image2, image1, image0);
  813. image = colorImage.ScaleImage((int)nWidth, (int)nHeight);
  814. System.GC.Collect();
  815. return image;
  816. }
  817. }
  818. catch (System.Exception)
  819. {
  820. return null;
  821. }
  822. }
  823. #endregion
  824. #region 属性通知
  825. /// <summary>
  826. /// Occurs when a property value changes.
  827. /// </summary>
  828. public event PropertyChangedEventHandler PropertyChanged;
  829. /// <summary>
  830. /// Checks if a property already matches a desired value. Sets the property and
  831. /// notifies listeners only when necessary.
  832. /// </summary>
  833. /// <typeparam name="T">Type of the property.</typeparam>
  834. /// <param name="storage">Reference to a property with both getter and setter.</param>
  835. /// <param name="value">Desired value for the property.</param>
  836. /// <param name="propertyName">Name of the property used to notify listeners. This
  837. /// value is optional and can be provided automatically when invoked from compilers that
  838. /// support CallerMemberName.</param>
  839. /// <returns>True if the value was changed, false if the existing value matched the
  840. /// desired value.</returns>
  841. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  842. {
  843. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  844. storage = value;
  845. RaisePropertyChanged(propertyName);
  846. return true;
  847. }
  848. /// <summary>
  849. /// Checks if a property already matches a desired value. Sets the property and
  850. /// notifies listeners only when necessary.
  851. /// </summary>
  852. /// <typeparam name="T">Type of the property.</typeparam>
  853. /// <param name="storage">Reference to a property with both getter and setter.</param>
  854. /// <param name="value">Desired value for the property.</param>
  855. /// <param name="propertyName">Name of the property used to notify listeners. This
  856. /// value is optional and can be provided automatically when invoked from compilers that
  857. /// support CallerMemberName.</param>
  858. /// <param name="onChanged">Action that is called after the property value has been changed.</param>
  859. /// <returns>True if the value was changed, false if the existing value matched the
  860. /// desired value.</returns>
  861. protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
  862. {
  863. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  864. storage = value;
  865. onChanged?.Invoke();
  866. RaisePropertyChanged(propertyName);
  867. return true;
  868. }
  869. /// <summary>
  870. /// Raises this object's PropertyChanged event.
  871. /// </summary>
  872. /// <param name="propertyName">Name of the property used to notify listeners. This
  873. /// value is optional and can be provided automatically when invoked from compilers
  874. /// that support <see cref="CallerMemberNameAttribute"/>.</param>
  875. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  876. {
  877. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  878. }
  879. /// <summary>
  880. /// Raises this object's PropertyChanged event.
  881. /// </summary>
  882. /// <param name="args">The PropertyChangedEventArgs</param>
  883. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
  884. {
  885. PropertyChanged?.Invoke(this, args);
  886. }
  887. #endregion
  888. }
  889. }