BaslerCamera.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using TeamAAS_VP.Enums;
  11. using TeamAAS_VP.Interfaces;
  12. using Cognex.VisionPro;
  13. using Basler.Pylon;
  14. using System.IO;
  15. using System.Drawing.Imaging;
  16. using System.Drawing;
  17. using System.Diagnostics;
  18. using ControlzEx.Standard;
  19. using System.Windows.Media.Media3D;
  20. using MvCamCtrl.NET;
  21. using TeamAAS_VP.Models;
  22. using Microsoft.Win32;
  23. using TeamAAS_VP.Resources.Languages;
  24. //using System.Drawing;
  25. //using System.Drawing.Imaging;
  26. namespace TeamAAS_VP.Core.Cameras
  27. {
  28. public class BaslerCamera : CameraBase, Interfaces.ICamera, INotifyPropertyChanged
  29. {
  30. #region 字段
  31. private Basler.Pylon.Camera m_MyCamera;
  32. private Thread m_hReceiveThread;
  33. UInt32 m_nRowStep = 0;
  34. // The pixel data converter is used for converting grabbed images to a pixel format that can be displayed.
  35. private PixelDataConverter converter = new PixelDataConverter();
  36. #endregion
  37. #region 属性
  38. public CameraBrand CameraBrand { get => CameraBrand.Basler_Pylon; }
  39. public string Name { get; private set; }
  40. public Guid ID { get; private set; }
  41. public int Index { get; set; }
  42. public string ManufacturerName { get; private set; }
  43. public bool IsFindByIp { get; private set; }
  44. public string ModelName { get; private set; }
  45. public string SerialNumber { get; private set; }
  46. public string CameraIp { get; private set; }
  47. public CameraType CameraType { get; private set; }
  48. public UInt32 ImageWidth { get; private set; }
  49. public UInt32 ImageHeight { get; private set; }
  50. private bool _IsGrabbing;
  51. /// <summary>
  52. /// 正在采集
  53. /// </summary>
  54. public bool IsGrabbing
  55. {
  56. get { return _IsGrabbing; }
  57. private set { SetProperty(ref _IsGrabbing, value); }
  58. }
  59. private ICogImage _Image;
  60. public ICogImage Image
  61. {
  62. get { return _Image; }
  63. private set { SetProperty(ref _Image, value); }
  64. }
  65. public bool IsConnected { get; private set; }
  66. public ICameraInfo CameraInfo { get; private set; }
  67. /// <summary>
  68. /// 采集用时
  69. /// </summary>
  70. public TimeSpan TotalTime { get; private set; }
  71. /// <summary>
  72. /// 错误信息
  73. /// </summary>
  74. public string ErrorMessage { get; private set; }
  75. #endregion
  76. #region 事件
  77. public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
  78. public event Action<Guid, bool> CameraConnectChangedEvent;
  79. #endregion
  80. public BaslerCamera(Guid id, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
  81. {
  82. ID = id;
  83. Name = serialNumber;
  84. Index = index;
  85. CameraIp = cameraip;
  86. SerialNumber = serialNumber;
  87. IsFindByIp = isFindByIp;
  88. List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
  89. foreach (ICameraInfo cameraInfo in allCameraInfos)
  90. {
  91. if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
  92. {
  93. if (IsFindByIp)
  94. {
  95. if (cameraInfo[CameraInfoKey.DeviceIpAddress] == CameraIp)
  96. {
  97. CameraInfo = cameraInfo;
  98. m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
  99. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
  100. ModelName = cameraInfo[CameraInfoKey.ModelName];
  101. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
  102. CameraType = CameraType.GIGE;
  103. m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
  104. m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
  105. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  106. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  107. //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
  108. break;
  109. }
  110. }
  111. else
  112. {
  113. if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
  114. {
  115. CameraInfo = cameraInfo;
  116. m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
  117. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
  118. ModelName = cameraInfo[CameraInfoKey.ModelName];
  119. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
  120. CameraType = CameraType.GIGE;
  121. CameraIp= cameraInfo[CameraInfoKey.DeviceIpAddress];
  122. m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
  123. m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
  124. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  125. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  126. //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
  127. break;
  128. }
  129. }
  130. }
  131. else
  132. {
  133. if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
  134. {
  135. CameraInfo = cameraInfo;
  136. m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
  137. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
  138. ModelName = cameraInfo[CameraInfoKey.ModelName];
  139. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
  140. CameraType = CameraType.USB;
  141. m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
  142. m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
  143. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  144. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  145. //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
  146. break;
  147. }
  148. }
  149. }
  150. IsConnected = false;
  151. }
  152. #region 方法
  153. /// <summary>
  154. /// 获取设备
  155. /// </summary>
  156. /// <returns></returns>
  157. public static CameraInfo[] GetDevices()
  158. {
  159. List<CameraInfo> cameras = new List<CameraInfo>();
  160. try
  161. {
  162. if (!CheckSoftwareInstalled().isInstalled)
  163. {
  164. LogHelper.WriteLogInfo(Lang.未安装pylon7);
  165. return cameras.ToArray();
  166. }
  167. List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
  168. int i = 0;
  169. foreach (ICameraInfo cameraInfo in allCameraInfos)
  170. {
  171. if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
  172. {
  173. cameras.Add(new Models.CameraInfo()
  174. {
  175. CameraNo = i + 1,
  176. CameraName = cameraInfo[CameraInfoKey.FullName],
  177. CameraBrand = CameraBrand.Basler_Pylon,
  178. CameraType = CameraType.GIGE,
  179. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
  180. Model = cameraInfo[CameraInfoKey.ModelName],
  181. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
  182. CameraIp = cameraInfo[CameraInfoKey.DeviceIpAddress],
  183. IsFindByIp = true,
  184. });
  185. }
  186. else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("usb"))
  187. {
  188. cameras.Add(new Models.CameraInfo()
  189. {
  190. CameraNo = i + 1,
  191. CameraName = cameraInfo[CameraInfoKey.FullName],
  192. CameraBrand = CameraBrand.Basler_Pylon,
  193. CameraType = CameraType.USB,
  194. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
  195. Model = cameraInfo[CameraInfoKey.ModelName],
  196. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
  197. CameraIp = "",
  198. });
  199. }
  200. else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("link"))
  201. {
  202. cameras.Add(new Models.CameraInfo()
  203. {
  204. CameraNo = i + 1,
  205. CameraName = cameraInfo[CameraInfoKey.FullName],
  206. CameraBrand = CameraBrand.Basler_Pylon,
  207. CameraType = CameraType.Link,
  208. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
  209. Model = cameraInfo[CameraInfoKey.ModelName],
  210. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
  211. CameraIp = "",
  212. });
  213. }
  214. else
  215. {
  216. cameras.Add(new Models.CameraInfo()
  217. {
  218. CameraNo = i + 1,
  219. CameraName = cameraInfo[CameraInfoKey.FullName],
  220. CameraBrand = CameraBrand.Basler_Pylon,
  221. CameraType = CameraType.Unknown,
  222. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
  223. Model = cameraInfo[CameraInfoKey.ModelName],
  224. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
  225. CameraIp = "",
  226. });
  227. }
  228. i++;
  229. }
  230. }
  231. catch (Exception ex)
  232. {
  233. LogHelper.WriteLogError(Lang.搜索巴斯勒相机列表时出错, ex);
  234. }
  235. return cameras.ToArray();
  236. }
  237. /// <summary>
  238. /// 检查相机软件是否安装
  239. /// </summary>
  240. /// <returns></returns>
  241. public static (bool isInstalled, string version) CheckSoftwareInstalled()
  242. {
  243. string softwareName = "pylon 7 Camera Software";
  244. string softwareVersion = "7.5.0.15658";
  245. string[] registryPaths = new[]
  246. {
  247. @"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
  248. @"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  249. };
  250. foreach (var path in registryPaths)
  251. {
  252. using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
  253. {
  254. if (key == null) continue;
  255. foreach (string subKeyName in key.GetSubKeyNames())
  256. {
  257. using (RegistryKey subKey = key.OpenSubKey(subKeyName))
  258. {
  259. string displayName = subKey.GetValue("DisplayName")?.ToString();
  260. if (displayName != null && displayName.Contains(softwareName))
  261. {
  262. string version = subKey.GetValue("DisplayVersion")?.ToString();
  263. Version v1 = new Version(version);
  264. Version v2 = new Version(softwareVersion);
  265. if (v1 >= v2)
  266. {
  267. return (true, version);
  268. }
  269. else
  270. {
  271. return (false, version);
  272. }
  273. }
  274. }
  275. }
  276. }
  277. }
  278. return (false, "");
  279. }
  280. /// <summary>
  281. /// 打开相机
  282. /// </summary>
  283. /// <returns></returns>
  284. /// <exception cref="Exception"></exception>
  285. public bool OpenDevice()
  286. {
  287. EnterOperation();
  288. try
  289. {
  290. if (m_MyCamera == null)
  291. {
  292. List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
  293. foreach (ICameraInfo cameraInfo in allCameraInfos)
  294. {
  295. if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
  296. {
  297. if (IsFindByIp)
  298. {
  299. if (cameraInfo[CameraInfoKey.DeviceIpAddress] == CameraIp)
  300. {
  301. CameraInfo = cameraInfo;
  302. m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
  303. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
  304. ModelName = cameraInfo[CameraInfoKey.ModelName];
  305. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
  306. CameraType = CameraType.GIGE;
  307. m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
  308. m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
  309. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  310. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  311. //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
  312. break;
  313. }
  314. }
  315. else
  316. {
  317. if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
  318. {
  319. CameraInfo = cameraInfo;
  320. m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
  321. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
  322. ModelName = cameraInfo[CameraInfoKey.ModelName];
  323. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
  324. CameraType = CameraType.GIGE;
  325. CameraIp = cameraInfo[CameraInfoKey.DeviceIpAddress];
  326. m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
  327. m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
  328. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  329. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  330. //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
  331. break;
  332. }
  333. }
  334. }
  335. else
  336. {
  337. if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
  338. {
  339. CameraInfo = cameraInfo;
  340. m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
  341. ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
  342. ModelName = cameraInfo[CameraInfoKey.ModelName];
  343. SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
  344. CameraType = CameraType.USB;
  345. m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
  346. m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
  347. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  348. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  349. //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
  350. break;
  351. }
  352. }
  353. }
  354. if (m_MyCamera == null)
  355. {
  356. throw new Exception(Lang.没有识别到相机);
  357. }
  358. }
  359. if (!m_MyCamera.IsOpen)
  360. {
  361. m_MyCamera.Open();
  362. m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
  363. m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
  364. m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
  365. }
  366. IsConnected = m_MyCamera.IsConnected;
  367. return IsConnected;
  368. }
  369. finally
  370. {
  371. ExitOperation();
  372. }
  373. }
  374. /// <summary>
  375. /// 打开相机异步
  376. /// </summary>
  377. /// <returns></returns>
  378. public Task<bool> OpenDeviceAsync()
  379. {
  380. return Task.Run(() =>
  381. {
  382. return OpenDevice();
  383. });
  384. }
  385. private void M_MyCamera_CameraClosed(object sender, EventArgs e)
  386. {
  387. CameraConnectChangedEvent?.Invoke(ID, false);
  388. }
  389. private void M_MyCamera_CameraOpened(object sender, EventArgs e)
  390. {
  391. CameraConnectChangedEvent?.Invoke(ID, true);
  392. }
  393. /// <summary>
  394. /// 关闭相机
  395. /// </summary>
  396. public void CloseDevice()
  397. {
  398. EnterOperation();
  399. try
  400. {
  401. if (m_MyCamera != null)
  402. {
  403. if (m_MyCamera.IsOpen)
  404. {
  405. m_MyCamera.Close();
  406. m_MyCamera.CameraOpened -= Configuration.AcquireContinuous; // 软触发打开
  407. m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
  408. m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
  409. IsConnected = m_MyCamera.IsConnected;
  410. m_MyCamera.Dispose();
  411. }
  412. }
  413. }
  414. finally
  415. {
  416. ExitOperation();
  417. }
  418. }
  419. /// <summary>
  420. /// 采集图像
  421. /// </summary>
  422. /// <returns></returns>
  423. public ICogImage Grab()
  424. {
  425. EnterOperation();
  426. try
  427. {
  428. Stopwatch sw = Stopwatch.StartNew();
  429. if (m_MyCamera == null)
  430. {
  431. throw new Exception(Lang.相机未连接);
  432. }
  433. if (!m_MyCamera.IsOpen)
  434. {
  435. m_MyCamera.Open();
  436. m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
  437. m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
  438. m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
  439. }
  440. if (!m_MyCamera.StreamGrabber.IsGrabbing)
  441. {
  442. // Start grabbing.
  443. m_MyCamera.StreamGrabber.Start();
  444. }
  445. bool Succeed = false;
  446. IGrabResult grabResult = null;
  447. for (int i = 0; i < 5; i++)
  448. {
  449. try
  450. {
  451. m_MyCamera.ExecuteSoftwareTrigger();
  452. // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
  453. grabResult = m_MyCamera.StreamGrabber.RetrieveResult(1000, TimeoutHandling.ThrowException);
  454. if (grabResult != null && grabResult.GrabSucceeded)
  455. {
  456. ErrorMessage = "";
  457. Succeed = true;
  458. break;
  459. }
  460. else
  461. {
  462. ErrorMessage = grabResult.ErrorDescription;
  463. }
  464. }
  465. catch (Exception ex)
  466. {
  467. ErrorMessage = ex.Message;
  468. m_MyCamera.Close();
  469. m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
  470. m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
  471. m_MyCamera.Open();
  472. m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
  473. m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
  474. m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
  475. IsConnected = m_MyCamera.IsConnected;
  476. }
  477. finally
  478. {
  479. //m_MyCamera.StreamGrabber.Stop();
  480. }
  481. }
  482. if (!Succeed)
  483. {
  484. if (IsConnected)
  485. {
  486. IsConnected = false;
  487. CameraConnectChangedEvent?.Invoke(ID, false);
  488. }
  489. return null;
  490. }
  491. //m_MyCamera.StreamGrabber.Stop();
  492. Image = GrabResult2CogImage(grabResult);
  493. GC.Collect();
  494. grabResult.Dispose();
  495. TotalTime = sw.Elapsed;
  496. return Image;
  497. }
  498. finally
  499. {
  500. ExitOperation();
  501. }
  502. }
  503. private void InvertColors(IGrabResult result)
  504. {
  505. byte pixelSize = 255;
  506. byte[] data = (byte[])result.PixelData;
  507. for (long i = 0; i < data.Length; i++)
  508. {
  509. data[i] = (byte)((int)pixelSize - (int)data[i]);
  510. }
  511. }
  512. /// <summary>
  513. /// 转换成ICogImage图像
  514. /// </summary>
  515. /// <param name="nHeight"></param>
  516. /// <param name="nWidth"></param>
  517. /// <param name="pImageBuf"></param>
  518. /// <param name="enPixelType"></param>
  519. /// <returns></returns>
  520. public ICogImage ConvertToICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, Basler.Pylon.PixelType enPixelType)
  521. {
  522. // ch: 显示 || display
  523. try
  524. {
  525. if (enPixelType == Basler.Pylon.PixelType.Mono8)
  526. {
  527. CogImage8Root cogImage8Root = new CogImage8Root();
  528. cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
  529. CogImage8Grey cogImage8Grey = new CogImage8Grey();
  530. cogImage8Grey.SetRoot(cogImage8Root);
  531. return cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
  532. }
  533. else
  534. {
  535. CogImage8Root image0 = new CogImage8Root();
  536. IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
  537. image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
  538. CogImage8Root image1 = new CogImage8Root();
  539. IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + m_nRowStep);
  540. image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
  541. CogImage8Root image2 = new CogImage8Root();
  542. IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + m_nRowStep * 2);
  543. image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
  544. CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
  545. colorImage.SetRoots(image0, image1, image2);
  546. return colorImage.ScaleImage((int)nWidth, (int)nHeight);
  547. }
  548. }
  549. catch (System.Exception)
  550. {
  551. return null;
  552. }
  553. }
  554. /// <summary>
  555. /// 开始采集图像
  556. /// </summary>
  557. public void StartGrabbing()
  558. {
  559. EnterOperation();
  560. try
  561. {
  562. if (m_MyCamera == null)
  563. {
  564. throw new Exception(Lang.相机未连接);
  565. }
  566. if (!m_MyCamera.IsOpen)
  567. {
  568. throw new Exception(Lang.相机未打开);
  569. }
  570. m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
  571. //m_MyCamera.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
  572. if (IsGrabbing)
  573. return;
  574. if (!m_MyCamera.StreamGrabber.IsGrabbing)
  575. {
  576. // Start grabbing.
  577. m_MyCamera.StreamGrabber.Start();
  578. }
  579. lock (_stateLock)
  580. {
  581. IsGrabbing = true;
  582. }
  583. m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
  584. m_hReceiveThread.Start();
  585. }
  586. finally
  587. {
  588. ExitOperation();
  589. }
  590. }
  591. /// <summary>
  592. /// 停止采集图像
  593. /// </summary>
  594. public void StopGrabbing()
  595. {
  596. try
  597. {
  598. lock (_stateLock)
  599. {
  600. IsGrabbing = false;
  601. }
  602. Thread.Sleep(1000);
  603. if (m_hReceiveThread != null)
  604. {
  605. m_hReceiveThread.Abort();
  606. m_hReceiveThread = null;
  607. }
  608. if (m_MyCamera != null && m_MyCamera.StreamGrabber.IsGrabbing)
  609. {
  610. m_MyCamera.StreamGrabber.Stop();
  611. }
  612. }
  613. catch (Exception)
  614. {
  615. }
  616. }
  617. /// <summary>
  618. /// 设置曝光时间
  619. /// </summary>
  620. /// <param name="ExposureTime"></param>
  621. /// <returns></returns>
  622. public bool SetExposureTime(float ExposureTime)
  623. {
  624. EnterOperation();
  625. try
  626. {
  627. if (m_MyCamera == null)
  628. {
  629. return false;
  630. }
  631. if (m_MyCamera.Parameters.Contains(PLCamera.ExposureTimeAbs))
  632. {
  633. m_MyCamera.Parameters[PLCamera.ExposureTimeAbs].SetValue(ExposureTime);
  634. }
  635. else
  636. m_MyCamera.Parameters[PLCamera.ExposureTime].SetValue(ExposureTime);
  637. return true;
  638. }
  639. finally
  640. {
  641. ExitOperation();
  642. }
  643. }
  644. /// <summary>
  645. /// 获取曝光时间
  646. /// </summary>
  647. /// <returns></returns>
  648. public float GetExposureTime()
  649. {
  650. EnterOperation();
  651. try
  652. {
  653. if (m_MyCamera == null)
  654. {
  655. return 0;
  656. }
  657. if (m_MyCamera.Parameters.Contains(PLCamera.ExposureTimeAbs))
  658. {
  659. return (float)m_MyCamera.Parameters[PLCamera.ExposureTimeAbs].GetValue();
  660. }
  661. else
  662. return (float)m_MyCamera.Parameters[PLCamera.ExposureTime].GetValue();
  663. }
  664. finally
  665. {
  666. ExitOperation();
  667. }
  668. }
  669. /// <summary>
  670. /// 设置增益
  671. /// </summary>
  672. /// <param name="Gain"></param>
  673. /// <returns></returns>
  674. public bool SetGain(float Gain)
  675. {
  676. EnterOperation();
  677. try
  678. {
  679. if (m_MyCamera == null)
  680. {
  681. return false;
  682. }
  683. if (m_MyCamera.Parameters.Contains(PLCamera.Gain))
  684. {
  685. m_MyCamera.Parameters[PLCamera.Gain].SetValue(Gain);
  686. }
  687. else if (m_MyCamera.Parameters.Contains(PLCamera.GainRaw))
  688. {
  689. m_MyCamera.Parameters[PLCamera.GainRaw].SetValue((int)Gain);
  690. }
  691. else if (m_MyCamera.Parameters.Contains(PLCamera.GainAbs))
  692. {
  693. m_MyCamera.Parameters[PLCamera.GainAbs].SetValue(Gain);
  694. }
  695. return true;
  696. }
  697. finally
  698. {
  699. ExitOperation();
  700. }
  701. }
  702. /// <summary>
  703. /// 获取增益
  704. /// </summary>
  705. /// <returns></returns>
  706. public float GetGain()
  707. {
  708. EnterOperation();
  709. try
  710. {
  711. if (m_MyCamera.Parameters.Contains(PLCamera.Gain))
  712. {
  713. return (float)m_MyCamera.Parameters[PLCamera.Gain].GetValue();
  714. }
  715. else
  716. return (float)m_MyCamera.Parameters[PLCamera.GainAbs].GetValue();
  717. }
  718. finally
  719. {
  720. ExitOperation();
  721. }
  722. }
  723. private void GetStreamThreadProc()
  724. {
  725. while (IsGrabbing)
  726. {
  727. Stopwatch sw = Stopwatch.StartNew();
  728. try
  729. {
  730. if (!m_MyCamera.IsConnected)
  731. {
  732. m_MyCamera.Close();
  733. m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
  734. m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
  735. m_MyCamera = new Basler.Pylon.Camera(CameraInfo);
  736. m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
  737. m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
  738. }
  739. if (!m_MyCamera.IsOpen)
  740. {
  741. m_MyCamera.Open();
  742. IsConnected = m_MyCamera.IsConnected;
  743. }
  744. m_MyCamera.ExecuteSoftwareTrigger();
  745. // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
  746. IGrabResult grabResult = m_MyCamera.StreamGrabber.RetrieveResult(1000, TimeoutHandling.ThrowException);
  747. using (grabResult)
  748. {
  749. // Image grabbed successfully?
  750. if (grabResult != null && grabResult.GrabSucceeded)
  751. {
  752. ErrorMessage = "";
  753. Image = GrabResult2CogImage(grabResult);
  754. TotalTime = sw.Elapsed;
  755. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
  756. }
  757. else
  758. {
  759. TotalTime = sw.Elapsed;
  760. ErrorMessage = grabResult.ErrorDescription;
  761. ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
  762. }
  763. }
  764. }
  765. catch (Exception ex)
  766. {
  767. TotalTime = sw.Elapsed;
  768. ImageCallbackEvent?.Invoke(Image, TotalTime, ex.Message);
  769. }
  770. Thread.Sleep(10);
  771. GC.Collect();
  772. }
  773. IsGrabbing = false;
  774. }
  775. /// <summary>
  776. /// 图像是否为彩色
  777. /// </summary>
  778. /// <param name="enType"></param>
  779. /// <returns></returns>
  780. private bool IsColorPixelFormat(Basler.Pylon.PixelType enType)
  781. {
  782. switch (enType)
  783. {
  784. case Basler.Pylon.PixelType.RGB8packed:
  785. case Basler.Pylon.PixelType.BGR8packed:
  786. case Basler.Pylon.PixelType.RGBA8packed:
  787. case Basler.Pylon.PixelType.BGRA8packed:
  788. case Basler.Pylon.PixelType.YUV422packed:
  789. case Basler.Pylon.PixelType.YUV422_YUYV_Packed:
  790. case Basler.Pylon.PixelType.BayerGR8:
  791. case Basler.Pylon.PixelType.BayerRG8:
  792. case Basler.Pylon.PixelType.BayerGB8:
  793. case Basler.Pylon.PixelType.BayerBG8:
  794. case Basler.Pylon.PixelType.BayerGB10:
  795. case Basler.Pylon.PixelType.BayerGB10pp:
  796. case Basler.Pylon.PixelType.BayerBG10:
  797. case Basler.Pylon.PixelType.BayerBG10pp:
  798. case Basler.Pylon.PixelType.BayerRG10:
  799. case Basler.Pylon.PixelType.BayerRG10pp:
  800. case Basler.Pylon.PixelType.BayerGR10:
  801. case Basler.Pylon.PixelType.BayerGR10pp:
  802. case Basler.Pylon.PixelType.BayerGB12:
  803. case Basler.Pylon.PixelType.BayerGB12p:
  804. case Basler.Pylon.PixelType.BayerBG12:
  805. case Basler.Pylon.PixelType.BayerBG12Packed:
  806. case Basler.Pylon.PixelType.BayerRG12:
  807. case Basler.Pylon.PixelType.BayerRG12Packed:
  808. case Basler.Pylon.PixelType.BayerGR12:
  809. case Basler.Pylon.PixelType.BayerGR12Packed:
  810. return true;
  811. default:
  812. return false;
  813. }
  814. }
  815. /// <summary>
  816. /// 图像是否为Mono格式
  817. /// </summary>
  818. /// <param name="enType"></param>
  819. /// <returns></returns>
  820. private bool IsMonoPixelFormat(Basler.Pylon.PixelType enType)
  821. {
  822. switch (enType)
  823. {
  824. case Basler.Pylon.PixelType.Mono8:
  825. case Basler.Pylon.PixelType.Mono10:
  826. case Basler.Pylon.PixelType.Mono10packed:
  827. case Basler.Pylon.PixelType.Mono12:
  828. case Basler.Pylon.PixelType.Mono12packed:
  829. return true;
  830. default:
  831. return false;
  832. }
  833. }
  834. /// <summary>
  835. /// 将从相机获取的图像IGrabResult转换为CogImage图像
  836. /// <paramref name="grabResult"/> 从相机获取的图像 IGrabResult </param>
  837. /// </summary>
  838. private ICogImage GrabResult2CogImage(IGrabResult grabResult)
  839. {
  840. if (grabResult == null) return null;
  841. byte[] pixelData = grabResult.PixelData as byte[];
  842. GCHandle pixelHandle = default;
  843. bool pixelPinned = false;
  844. GCHandle dstHandle = default;
  845. bool dstPinned = false;
  846. ICogImage result = null;
  847. try
  848. {
  849. // 尽量 pin 原始像素数据(如果存在)
  850. if (pixelData != null && pixelData.Length > 0)
  851. {
  852. pixelHandle = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
  853. pixelPinned = true;
  854. }
  855. IntPtr pixelPointer = pixelPinned ? pixelHandle.AddrOfPinnedObject() : IntPtr.Zero;
  856. // 彩色图像处理
  857. if (IsColorPixelFormat(grabResult.PixelTypeValue))
  858. {
  859. // 使用 using 确保 Bitmap 及时释放
  860. using (Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb))
  861. {
  862. BitmapData bmpData = null;
  863. try
  864. {
  865. bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
  866. // 使用成员 converter 将 grabResult 转换到 bitmap 的缓冲区
  867. converter.OutputPixelFormat = PixelType.BGRA8packed;
  868. IntPtr ptrBmp = bmpData.Scan0;
  869. converter.Convert(ptrBmp, Math.Abs(bmpData.Stride) * bitmap.Height, grabResult);
  870. }
  871. finally
  872. {
  873. if (bmpData != null)
  874. {
  875. try { bitmap.UnlockBits(bmpData); } catch { }
  876. }
  877. }
  878. // 构造 Cognex 图像并返回副本(ScaleImage 通常返回独立图像)
  879. CogImage24PlanarColor colorImage = null;
  880. try
  881. {
  882. colorImage = new CogImage24PlanarColor(bitmap);
  883. result = colorImage.ScaleImage(bitmap.Width, bitmap.Height);
  884. }
  885. finally
  886. {
  887. // colorImage 若实现了 IDisposable 则释放(安全检查)
  888. (colorImage as IDisposable)?.Dispose();
  889. }
  890. }
  891. return result;
  892. }
  893. // 单通道(Mono)图像处理
  894. else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
  895. {
  896. Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Mono8;
  897. uint nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height;
  898. IntPtr pTemp = IntPtr.Zero;
  899. if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
  900. {
  901. // 直接使用已 pin 的原始数据指针
  902. if (!pixelPinned)
  903. {
  904. // 如果原始不是 byte[],尝试从 grabResult 获取 PixelData(若支持)
  905. byte[] alt = grabResult.PixelData as byte[];
  906. if (alt != null)
  907. {
  908. pixelHandle = GCHandle.Alloc(alt, GCHandleType.Pinned);
  909. pixelPinned = true;
  910. pixelPointer = pixelHandle.AddrOfPinnedObject();
  911. }
  912. }
  913. pTemp = pixelPointer;
  914. }
  915. else
  916. {
  917. // 为转换后的 Mono8 数据分配临时缓冲并 pin
  918. byte[] dstBuffer = new byte[nSaveImageNeedSize];
  919. dstHandle = GCHandle.Alloc(dstBuffer, GCHandleType.Pinned);
  920. dstPinned = true;
  921. pTemp = dstHandle.AddrOfPinnedObject();
  922. // 使用局部的 PixelDataConverter 转换为 Mono8
  923. var pixelConverter = new Basler.Pylon.PixelDataConverter();
  924. pixelConverter.OutputPixelFormat = Basler.Pylon.PixelType.Mono8;
  925. pixelConverter.Convert(pTemp, nSaveImageNeedSize, grabResult);
  926. }
  927. if (pTemp == IntPtr.Zero)
  928. {
  929. return null;
  930. }
  931. // ConvertToICogImage 内部会做 ScaleImage,通常会产生独立拷贝
  932. result = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
  933. return result;
  934. }
  935. return null;
  936. }
  937. finally
  938. {
  939. // 释放所有固定句柄,确保及时释放 pin 状态
  940. try
  941. {
  942. if (dstPinned)
  943. {
  944. dstHandle.Free();
  945. dstPinned = false;
  946. }
  947. }
  948. catch { }
  949. try
  950. {
  951. if (pixelPinned)
  952. {
  953. pixelHandle.Free();
  954. pixelPinned = false;
  955. }
  956. }
  957. catch { }
  958. }
  959. }
  960. #endregion
  961. #region 属性通知
  962. /// <summary>
  963. /// Occurs when a property value changes.
  964. /// </summary>
  965. public event PropertyChangedEventHandler PropertyChanged;
  966. /// <summary>
  967. /// Checks if a property already matches a desired value. Sets the property and
  968. /// notifies listeners only when necessary.
  969. /// </summary>
  970. /// <typeparam name="T">Type of the property.</typeparam>
  971. /// <param name="storage">Reference to a property with both getter and setter.</param>
  972. /// <param name="value">Desired value for the property.</param>
  973. /// <param name="propertyName">Name of the property used to notify listeners. This
  974. /// value is optional and can be provided automatically when invoked from compilers that
  975. /// support CallerMemberName.</param>
  976. /// <returns>True if the value was changed, false if the existing value matched the
  977. /// desired value.</returns>
  978. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  979. {
  980. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  981. storage = value;
  982. RaisePropertyChanged(propertyName);
  983. return true;
  984. }
  985. /// <summary>
  986. /// Checks if a property already matches a desired value. Sets the property and
  987. /// notifies listeners only when necessary.
  988. /// </summary>
  989. /// <typeparam name="T">Type of the property.</typeparam>
  990. /// <param name="storage">Reference to a property with both getter and setter.</param>
  991. /// <param name="value">Desired value for the property.</param>
  992. /// <param name="propertyName">Name of the property used to notify listeners. This
  993. /// value is optional and can be provided automatically when invoked from compilers that
  994. /// support CallerMemberName.</param>
  995. /// <param name="onChanged">Action that is called after the property value has been changed.</param>
  996. /// <returns>True if the value was changed, false if the existing value matched the
  997. /// desired value.</returns>
  998. protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
  999. {
  1000. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  1001. storage = value;
  1002. onChanged?.Invoke();
  1003. RaisePropertyChanged(propertyName);
  1004. return true;
  1005. }
  1006. /// <summary>
  1007. /// Raises this object's PropertyChanged event.
  1008. /// </summary>
  1009. /// <param name="propertyName">Name of the property used to notify listeners. This
  1010. /// value is optional and can be provided automatically when invoked from compilers
  1011. /// that support <see cref="CallerMemberNameAttribute"/>.</param>
  1012. protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
  1013. {
  1014. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  1015. }
  1016. /// <summary>
  1017. /// Raises this object's PropertyChanged event.
  1018. /// </summary>
  1019. /// <param name="args">The PropertyChangedEventArgs</param>
  1020. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
  1021. {
  1022. PropertyChanged?.Invoke(this, args);
  1023. }
  1024. #endregion
  1025. }
  1026. }