OptCamera.cs 37 KB

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