OptCamera.cs 37 KB

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