OptCamera.cs 39 KB

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