OptCamera.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. using Cognex.VisionPro;
  2. using Microsoft.Win32;
  3. using NPOI.SS.Formula.Eval;
  4. using SciCamera.Net;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Runtime.CompilerServices;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using TeamAAS_VP.Enums;
  18. using TeamAAS_VP.Interfaces;
  19. using TeamAAS_VP.Models;
  20. using TeamAAS_VP.Resources.Languages;
  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(Lang.未安装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(Lang.搜索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(Lang.没有发现相机);
  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. if (!IsConnected)
  313. {
  314. CameraConnectChangedEvent?.Invoke(ID, true);
  315. }
  316. IsConnected = mvCameraAcq.IsDeviceOpen();
  317. if (IsConnected)
  318. {
  319. mvCameraAcq.StartGrabbing();
  320. }
  321. return IsConnected;
  322. }
  323. finally
  324. {
  325. //_operationSemaphore.Release();
  326. }
  327. }
  328. /// <summary>
  329. /// 打开相机异步
  330. /// </summary>
  331. /// <returns></returns>
  332. public Task<bool> OpenDeviceAsync()
  333. {
  334. return Task.Run(() =>
  335. {
  336. return OpenDevice();
  337. });
  338. }
  339. /// <summary>
  340. /// 关闭相机
  341. /// </summary>
  342. public void CloseDevice()
  343. {
  344. // ch:关闭设备 | en:Close Device
  345. //_operationSemaphore.Wait();
  346. try
  347. {
  348. mvCameraAcq.StopGrabbing();
  349. mvCameraAcq.CloseDevice();
  350. }
  351. finally
  352. {
  353. //_operationSemaphore.Release();
  354. }
  355. }
  356. /// <summary>
  357. /// 采集图像
  358. /// </summary>
  359. /// <returns></returns>
  360. public ICogImage Grab()
  361. {
  362. //_operationSemaphore.Wait();
  363. uint nReVal = SciCam.SCI_CAMERA_OK;
  364. IntPtr payload = IntPtr.Zero;
  365. try
  366. {
  367. Stopwatch sw = Stopwatch.StartNew();
  368. for (int i = 0; i < 5; i++)
  369. {
  370. try
  371. {
  372. if (!mvCameraAcq.IsDeviceOpen())
  373. {
  374. OpenDevice();
  375. }
  376. //nReVal = mvCameraAcq.StartGrabbing();
  377. nReVal = mvCameraAcq.Grab(ref payload);
  378. if (nReVal == SciCam.SCI_CAMERA_OK)
  379. {
  380. Image = GetConvertedInfo(payload);
  381. mvCameraAcq.FreePayload(payload);
  382. //nReVal = mvCameraAcq.StopGrabbing();
  383. TotalTime = sw.Elapsed;
  384. return Image;
  385. }
  386. else
  387. {
  388. nReVal = mvCameraAcq.FreePayload(payload);
  389. //nReVal = mvCameraAcq.StopGrabbing();
  390. //_operationSemaphore.Release();
  391. CloseDevice();
  392. OpenDevice();
  393. ErrorMessage = Lang.图像采集失败;
  394. }
  395. }
  396. catch (Exception ex)
  397. {
  398. //_operationSemaphore.Release();
  399. CloseDevice();
  400. OpenDevice();
  401. ErrorMessage = ex.Message;
  402. }
  403. }
  404. if (IsConnected)
  405. {
  406. IsConnected = false;
  407. CameraConnectChangedEvent?.Invoke(ID, false);
  408. }
  409. return null;
  410. }
  411. finally
  412. {
  413. //_operationSemaphore.Release();
  414. }
  415. }
  416. /// <summary>
  417. /// 开始采集图像
  418. /// </summary>
  419. public void StartGrabbing()
  420. {
  421. lock (_stateLock)
  422. {
  423. if (IsGrabbing)
  424. return;
  425. IsGrabbing = true;
  426. }
  427. m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
  428. m_hReceiveThread.Start();
  429. }
  430. /// <summary>
  431. /// 停止采集图像
  432. /// </summary>
  433. public void StopGrabbing()
  434. {
  435. try
  436. {
  437. lock (_stateLock)
  438. {
  439. IsGrabbing = false;
  440. }
  441. if (m_hReceiveThread != null)
  442. {
  443. m_hReceiveThread.Abort();
  444. m_hReceiveThread = null;
  445. }
  446. }
  447. catch (Exception)
  448. {
  449. }
  450. }
  451. /// <summary>
  452. /// 设置曝光时间
  453. /// </summary>
  454. /// <param name="ExposureTime"></param>
  455. /// <returns></returns>
  456. public bool SetExposureTime(float ExposureTime)
  457. {
  458. //_operationSemaphore.Wait();
  459. try
  460. {
  461. if (!mvCameraAcq.IsDeviceOpen())
  462. return false;
  463. uint nReVal = SciCam.SCI_CAMERA_OK;
  464. nReVal = mvCameraAcq.SetIntValue("ExposureTime", (int)ExposureTime);
  465. if (nReVal != SciCam.SCI_CAMERA_OK)
  466. {
  467. mvCameraAcq.SetFloatValue("ExposureTime", ExposureTime);
  468. }
  469. return true;
  470. }
  471. finally
  472. {
  473. //_operationSemaphore.Release();
  474. }
  475. }
  476. /// <summary>
  477. /// 获取曝光时间
  478. /// </summary>
  479. /// <returns></returns>
  480. public float GetExposureTime()
  481. {
  482. //_operationSemaphore.Wait();
  483. try
  484. {
  485. if (!mvCameraAcq.IsDeviceOpen())
  486. return 0;
  487. uint nReVal = SciCam.SCI_CAMERA_OK;
  488. SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
  489. nReVal = mvCameraAcq.GetIntValue("ExposureTime", ref iNodeVal);
  490. if (nReVal != SciCam.SCI_CAMERA_OK)
  491. {
  492. SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
  493. nReVal = mvCameraAcq.GetFloatValue("ExposureTime", ref fNodeVal);
  494. if (nReVal == SciCam.SCI_CAMERA_OK)
  495. {
  496. return (float)fNodeVal.dVal;
  497. }
  498. else
  499. {
  500. return 0;
  501. }
  502. }
  503. else
  504. {
  505. return (float)iNodeVal.nVal;
  506. }
  507. }
  508. finally
  509. {
  510. //_operationSemaphore.Release();
  511. }
  512. }
  513. /// <summary>
  514. /// 设置增益
  515. /// </summary>
  516. /// <param name="Gain"></param>
  517. /// <returns></returns>
  518. public bool SetGain(float Gain)
  519. {
  520. //_operationSemaphore.Wait();
  521. try
  522. {
  523. if (!mvCameraAcq.IsDeviceOpen())
  524. return false;
  525. uint nReVal = SciCam.SCI_CAMERA_OK;
  526. nReVal = mvCameraAcq.SetIntValue("Gain", (int)Gain);
  527. if (nReVal != SciCam.SCI_CAMERA_OK)
  528. {
  529. mvCameraAcq.SetFloatValue("Gain", Gain);
  530. }
  531. return true;
  532. }
  533. finally
  534. {
  535. //_operationSemaphore.Release();
  536. }
  537. }
  538. /// <summary>
  539. /// 获取增益
  540. /// </summary>
  541. /// <returns></returns>
  542. public float GetGain()
  543. {
  544. //_operationSemaphore.Wait();
  545. try
  546. {
  547. if (!mvCameraAcq.IsDeviceOpen())
  548. return 0;
  549. uint nReVal = SciCam.SCI_CAMERA_OK;
  550. SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
  551. nReVal = mvCameraAcq.GetIntValue("Gain", ref iNodeVal);
  552. if (nReVal != SciCam.SCI_CAMERA_OK)
  553. {
  554. SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
  555. nReVal = mvCameraAcq.GetFloatValue("Gain", ref fNodeVal);
  556. if (nReVal == SciCam.SCI_CAMERA_OK)
  557. {
  558. return (float)fNodeVal.dVal;
  559. }
  560. else
  561. {
  562. return 0;
  563. }
  564. }
  565. else
  566. {
  567. return (float)iNodeVal.nVal;
  568. }
  569. }
  570. finally
  571. {
  572. //_operationSemaphore.Release();
  573. }
  574. }
  575. private void GetStreamThreadProc()
  576. {
  577. while (IsGrabbing)
  578. {
  579. try
  580. {
  581. Grab();
  582. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
  583. }
  584. catch (Exception)
  585. {
  586. }
  587. Thread.Sleep(10);
  588. }
  589. IsGrabbing = false;
  590. }
  591. private ICogImage GetConvertedInfo(IntPtr payload)
  592. {
  593. if (payload == IntPtr.Zero)
  594. {
  595. return null;
  596. }
  597. SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE payloadAttribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
  598. uint nReVal = SciCam.PayloadGetAttribute(payload, ref payloadAttribute);
  599. if (nReVal != SciCam.SCI_CAMERA_OK)
  600. {
  601. return null;
  602. }
  603. bool imgIsComplete = payloadAttribute.isComplete;
  604. SciCam.SciCamPayloadMode payloadMode = payloadAttribute.payloadMode;
  605. SciCam.SciCamPixelType imgPixelType = payloadAttribute.imgAttr.pixelType;
  606. ulong imgWidth = payloadAttribute.imgAttr.width;
  607. ulong imgHeight = payloadAttribute.imgAttr.height;
  608. ulong framID = payloadAttribute.frameID;
  609. if (!imgIsComplete || payloadMode != SciCam.SciCamPayloadMode.SciCam_PayloadMode_2D)
  610. {
  611. return null;
  612. }
  613. IntPtr imgData = IntPtr.Zero;
  614. nReVal = SciCam.PayloadGetImage(payload, ref imgData);
  615. if (nReVal != SciCam.SCI_CAMERA_OK)
  616. {
  617. return null;
  618. }
  619. long destImgSize = 0;
  620. if (imgPixelType == SciCam.SciCamPixelType.Mono1p ||
  621. imgPixelType == SciCam.SciCamPixelType.Mono2p ||
  622. imgPixelType == SciCam.SciCamPixelType.Mono4p ||
  623. imgPixelType == SciCam.SciCamPixelType.Mono8s ||
  624. imgPixelType == SciCam.SciCamPixelType.Mono8 ||
  625. imgPixelType == SciCam.SciCamPixelType.Mono10 ||
  626. imgPixelType == SciCam.SciCamPixelType.Mono10p ||
  627. imgPixelType == SciCam.SciCamPixelType.Mono12 ||
  628. imgPixelType == SciCam.SciCamPixelType.Mono12p ||
  629. imgPixelType == SciCam.SciCamPixelType.Mono14 ||
  630. imgPixelType == SciCam.SciCamPixelType.Mono16 ||
  631. imgPixelType == SciCam.SciCamPixelType.Mono10Packed ||
  632. imgPixelType == SciCam.SciCamPixelType.Mono12Packed ||
  633. imgPixelType == SciCam.SciCamPixelType.Mono14p)
  634. {
  635. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, IntPtr.Zero, ref destImgSize, true);
  636. if (nReVal == SciCam.SCI_CAMERA_OK)
  637. {
  638. IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
  639. try
  640. {
  641. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, destImg, ref destImgSize, true);
  642. if (nReVal == SciCam.SCI_CAMERA_OK)
  643. {
  644. byte[] bBitmap = new byte[destImgSize];
  645. Marshal.Copy(destImg, bBitmap, 0, (int)destImgSize);
  646. Bitmap bitMap = new Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
  647. 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);
  648. Marshal.Copy(bBitmap, 0, bitmapData.Scan0, (int)destImgSize);
  649. bitMap.UnlockBits(bitmapData);
  650. //设置调色板
  651. System.Drawing.Imaging.ColorPalette palette = bitMap.Palette;
  652. for (int i = 0; i < 256; i++)
  653. {
  654. palette.Entries[i] = Color.FromArgb(i, i, i);
  655. }
  656. bitMap.Palette = palette;
  657. //显示图片
  658. return TransformICogImage((uint)imgHeight, (uint)imgWidth, destImg, SciCam.SciCamPixelType.Mono8);
  659. }
  660. }
  661. catch (Exception ex)
  662. {
  663. }
  664. finally
  665. {
  666. Marshal.FreeHGlobal(destImg);
  667. }
  668. }
  669. }
  670. else
  671. {
  672. nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, 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.RGB8, destImg, ref destImgSize, true);
  679. if (nReVal == SciCam.SCI_CAMERA_OK)
  680. {
  681. IntPtr pTemp = IntPtr.Zero;
  682. Byte[] byteArrImageData = new Byte[imgWidth * imgHeight * 3];
  683. unsafe
  684. {
  685. byte* pBufForSaveImage = (byte*)destImg;
  686. UInt32 nSupWidth = ((UInt32)imgWidth + (UInt32)3) & 0xfffffffc;
  687. for (int nRow = 0; nRow < (int)imgHeight; nRow++)
  688. {
  689. for (int col = 0; col < (int)imgWidth; col++)
  690. {
  691. byteArrImageData[nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col)];
  692. byteArrImageData[(int)imgWidth * (int)imgHeight + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 1)];
  693. byteArrImageData[(int)imgWidth * (int)imgHeight * 2 + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 2)];
  694. }
  695. }
  696. pTemp = Marshal.UnsafeAddrOfPinnedArrayElement(byteArrImageData, 0);
  697. }
  698. //显示图片
  699. return TransformICogImage((uint)imgHeight, (uint)imgWidth, pTemp, SciCam.SciCamPixelType.RGB8);
  700. }
  701. }
  702. catch (Exception ex)
  703. {
  704. }
  705. finally
  706. {
  707. Marshal.FreeHGlobal(destImg);
  708. }
  709. }
  710. }
  711. return null;
  712. }
  713. private ICogImage TransformICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, SciCam.SciCamPixelType enPixelType)
  714. {
  715. try
  716. {
  717. ICogImage image;
  718. if (enPixelType == SciCam.SciCamPixelType.Mono8)
  719. {
  720. CogImage8Root cogImage8Root = new CogImage8Root();
  721. cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
  722. CogImage8Grey cogImage8Grey = new CogImage8Grey();
  723. cogImage8Grey.SetRoot(cogImage8Root);
  724. image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
  725. System.GC.Collect();
  726. return image;
  727. }
  728. else
  729. {
  730. CogImage8Root image0 = new CogImage8Root();
  731. IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
  732. image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
  733. CogImage8Root image1 = new CogImage8Root();
  734. IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight);
  735. image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
  736. CogImage8Root image2 = new CogImage8Root();
  737. IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight * 2);
  738. image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
  739. CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
  740. //colorImage.SetRoots(image0, image1, image2);
  741. colorImage.SetRoots(image2, image1, image0);
  742. image = colorImage.ScaleImage((int)nWidth, (int)nHeight);
  743. System.GC.Collect();
  744. return image;
  745. }
  746. }
  747. catch (System.Exception)
  748. {
  749. return null;
  750. }
  751. }
  752. #endregion
  753. #region 属性通知
  754. /// <summary>
  755. /// Occurs when a property value changes.
  756. /// </summary>
  757. public event PropertyChangedEventHandler PropertyChanged;
  758. /// <summary>
  759. /// Checks if a property already matches a desired value. Sets the property and
  760. /// notifies listeners only when necessary.
  761. /// </summary>
  762. /// <typeparam name="T">Type of the property.</typeparam>
  763. /// <param name="storage">Reference to a property with both getter and setter.</param>
  764. /// <param name="value">Desired value for the property.</param>
  765. /// <param name="propertyName">Name of the property used to notify listeners. This
  766. /// value is optional and can be provided automatically when invoked from compilers that
  767. /// support CallerMemberName.</param>
  768. /// <returns>True if the value was changed, false if the existing value matched the
  769. /// desired value.</returns>
  770. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  771. {
  772. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  773. storage = value;
  774. RaisePropertyChanged(propertyName);
  775. return true;
  776. }
  777. /// <summary>
  778. /// Checks if a property already matches a desired value. Sets the property and
  779. /// notifies listeners only when necessary.
  780. /// </summary>
  781. /// <typeparam name="T">Type of the property.</typeparam>
  782. /// <param name="storage">Reference to a property with both getter and setter.</param>
  783. /// <param name="value">Desired value for the property.</param>
  784. /// <param name="propertyName">Name of the property used to notify listeners. This
  785. /// value is optional and can be provided automatically when invoked from compilers that
  786. /// support CallerMemberName.</param>
  787. /// <param name="onChanged">Action that is called after the property value has been changed.</param>
  788. /// <returns>True if the value was changed, false if the existing value matched the
  789. /// desired value.</returns>
  790. protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
  791. {
  792. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  793. storage = value;
  794. onChanged?.Invoke();
  795. RaisePropertyChanged(propertyName);
  796. return true;
  797. }
  798. /// <summary>
  799. /// Raises this object's PropertyChanged event.
  800. /// </summary>
  801. /// <param name="propertyName">Name of the property used to notify listeners. This
  802. /// value is optional and can be provided automatically when invoked from compilers
  803. /// that support <see cref="CallerMemberNameAttribute"/>.</param>
  804. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  805. {
  806. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  807. }
  808. /// <summary>
  809. /// Raises this object's PropertyChanged event.
  810. /// </summary>
  811. /// <param name="args">The PropertyChangedEventArgs</param>
  812. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
  813. {
  814. PropertyChanged?.Invoke(this, args);
  815. }
  816. #endregion
  817. }
  818. }