OptCamera.cs 38 KB

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