OptCamera.cs 37 KB

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