OptCamera.cs 37 KB

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