| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using TeamAAS_VP.Enums;
- using TeamAAS_VP.Interfaces;
- using Cognex.VisionPro;
- using Basler.Pylon;
- using System.IO;
- using System.Drawing.Imaging;
- using System.Drawing;
- using System.Diagnostics;
- using ControlzEx.Standard;
- using System.Windows.Media.Media3D;
- using MvCamCtrl.NET;
- using TeamAAS_VP.Models;
- using Microsoft.Win32;
- //using System.Drawing;
- //using System.Drawing.Imaging;
- namespace TeamAAS_VP.Core.Cameras
- {
- public class BaslerCamera : Interfaces.ICamera, INotifyPropertyChanged
- {
- #region 字段
- private Basler.Pylon.Camera m_MyCamera;
- private Thread m_hReceiveThread;
- UInt32 m_nRowStep = 0;
- // The pixel data converter is used for converting grabbed images to a pixel format that can be displayed.
- private PixelDataConverter converter = new PixelDataConverter();
- #endregion
- #region 属性
- public CameraBrand CameraBrand { get => CameraBrand.Basler_Pylon; }
- public string Name { get; private set; }
- public Guid ID { get; private set; }
- public string ManufacturerName { get; private set; }
- public string ModelName { get; private set; }
- public string SerialNumber { get; private set; }
- public CameraType CameraType { get; private set; }
- public UInt32 ImageWidth { get; private set; }
- public UInt32 ImageHeight { get; private set; }
- private bool _IsGrabbing;
- /// <summary>
- /// 正在采集
- /// </summary>
- public bool IsGrabbing
- {
- get { return _IsGrabbing; }
- private set { SetProperty(ref _IsGrabbing, value); }
- }
- private ICogImage _Image;
- public ICogImage Image
- {
- get { return _Image; }
- private set { SetProperty(ref _Image, value); }
- }
- public bool IsConnected { get; private set; }
- public ICameraInfo CameraInfo { get; private set; }
- /// <summary>
- /// 采集用时
- /// </summary>
- public TimeSpan TotalTime { get; private set; }
- /// <summary>
- /// 错误信息
- /// </summary>
- public string ErrorMessage { get; private set; }
- #endregion
- #region 事件
- public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
- public event Action<Guid, bool> CameraConnectChangedEvent;
- #endregion
- public BaslerCamera(Guid _ID, string _Name, string _SerialNumber)
- {
- ID = _ID;
- Name = _Name;
- SerialNumber = _SerialNumber;
- List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
- foreach (ICameraInfo cameraInfo in allCameraInfos)
- {
- if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
- {
- CameraInfo = cameraInfo;
- m_MyCamera = new Basler.Pylon.Camera(cameraInfo);
- ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
- ModelName = cameraInfo[CameraInfoKey.ModelName];
- SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
- if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
- {
- CameraType = CameraType.GIGE;
- }
- else
- {
- CameraType = CameraType.USB;
- }
- m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
- m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
- m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
- m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
- //m_MyCamera.StreamGrabber.ImageGrabbed += StreamGrabber_ImageGrabbed;
- break;
- }
- }
- IsConnected = false;
- }
- private void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)
- {
- Stopwatch sw = Stopwatch.StartNew();
- // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
- IGrabResult grabResult = e.GrabResult;
- using (grabResult)
- {
- // Image grabbed successfully?
- if (grabResult != null && grabResult.GrabSucceeded)
- {
- ErrorMessage = "";
- byte[] pixelData = grabResult.PixelData as byte[];
- IntPtr pixelPointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
- IntPtr pTemp = IntPtr.Zero;
- Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Undefined;
- UInt32 nSaveImageNeedSize = 0;
- if (IsColorPixelFormat(grabResult.PixelTypeValue))
- {
- Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
- // Lock the bits of the bitmap.
- BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
- converter.OutputPixelFormat = PixelType.BGRA8packed;
- // Place the pointer to the buffer of the bitmap.
- IntPtr ptrBmp = bmpData.Scan0;
- converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
- bitmap.UnlockBits(bmpData);
- CogImage24PlanarColor colorImage = new CogImage24PlanarColor(bitmap);
- Image = colorImage.ScaleImage((int)bitmap.Width, (int)bitmap.Height);
- }
- else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
- {
- enDstPixelType = Basler.Pylon.PixelType.Mono8;
- nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height * 3;
- if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
- {
- pTemp = pixelPointer;
- }
- else
- {
- // 其他格式Mono转为Mono8
- Basler.Pylon.PixelDataConverter converter = new PixelDataConverter();
- converter.OutputPixelFormat = Basler.Pylon.PixelType.RGB8packed;
- converter.Convert(pTemp, nSaveImageNeedSize, grabResult);
- }
- Image = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
- }
- TotalTime = sw.Elapsed;
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- else
- {
- TotalTime = sw.Elapsed;
- ErrorMessage = grabResult.ErrorDescription;
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- }
- }
- #region 方法
- /// <summary>
- /// 获取设备
- /// </summary>
- /// <returns></returns>
- public static CameraInfo[] GetDevices()
- {
- List<CameraInfo> cameras = new List<CameraInfo>();
- try
- {
- if (!CheckSoftwareInstalled().isInstalled)
- {
- LogHelper.WriteLogInfo("未安装pylon 7");
- return cameras.ToArray();
- }
- List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
- foreach (ICameraInfo cameraInfo in allCameraInfos)
- {
- if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraName = "",
- CameraBrand = CameraBrand.Basler_Pylon,
- CameraType = CameraType.GIGE,
- Id = Guid.NewGuid(),
- ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
- Model = cameraInfo[CameraInfoKey.ModelName],
- SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
- CameraIp = "",
- });
- }
- else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("usb"))
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraName = "",
- CameraBrand = CameraBrand.Basler_Pylon,
- CameraType = CameraType.USB,
- Id = Guid.NewGuid(),
- ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
- Model = cameraInfo[CameraInfoKey.ModelName],
- SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
- CameraIp = "",
- });
- }
- else if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("link"))
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraName = "",
- CameraBrand = CameraBrand.Basler_Pylon,
- CameraType = CameraType.Link,
- Id = Guid.NewGuid(),
- ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
- Model = cameraInfo[CameraInfoKey.ModelName],
- SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
- CameraIp = "",
- });
- }
- else
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraName = "",
- CameraBrand = CameraBrand.Basler_Pylon,
- CameraType = CameraType.Unknown,
- Id = Guid.NewGuid(),
- ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo],
- Model = cameraInfo[CameraInfoKey.ModelName],
- SerialNumber = cameraInfo[CameraInfoKey.SerialNumber],
- CameraIp = "",
- });
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("搜索巴斯勒相机列表时出错!", ex);
- }
- return cameras.ToArray();
- }
- /// <summary>
- /// 检查相机软件是否安装
- /// </summary>
- /// <returns></returns>
- public static (bool isInstalled, string version) CheckSoftwareInstalled()
- {
- string softwareName = "pylon 7 Camera Software";
- string softwareVersion = "7.5.0.15658";
- string[] registryPaths = new[]
- {
- @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
- @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
- };
- foreach (var path in registryPaths)
- {
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
- {
- if (key == null) continue;
- foreach (string subKeyName in key.GetSubKeyNames())
- {
- using (RegistryKey subKey = key.OpenSubKey(subKeyName))
- {
- string displayName = subKey.GetValue("DisplayName")?.ToString();
- if (displayName != null && displayName.Contains(softwareName))
- {
- string version = subKey.GetValue("DisplayVersion")?.ToString();
- Version v1 = new Version(version);
- Version v2 = new Version(softwareVersion);
- if (v1 >= v2)
- {
- return (true, version);
- }
- else
- {
- return (false, version);
- }
- }
- }
- }
- }
- }
- return (false, "");
- }
- /// <summary>
- /// 打开相机
- /// </summary>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public bool OpenDevice()
- {
- if (m_MyCamera == null)
- {
- List<Basler.Pylon.ICameraInfo> allCameraInfos = Basler.Pylon.CameraFinder.Enumerate();
- foreach (ICameraInfo cameraInfo in allCameraInfos)
- {
- if (cameraInfo[CameraInfoKey.SerialNumber] == SerialNumber)
- {
- CameraInfo = cameraInfo;
- m_MyCamera = new Basler.Pylon.Camera(CameraInfo);
- ManufacturerName = cameraInfo[CameraInfoKey.ManufacturerInfo];
- ModelName = cameraInfo[CameraInfoKey.ModelName];
- SerialNumber = cameraInfo[CameraInfoKey.SerialNumber];
- if (cameraInfo[CameraInfoKey.DeviceType].ToLower().Contains("gige"))
- {
- CameraType = CameraType.GIGE;
- }
- else
- {
- CameraType = CameraType.USB;
- }
- m_MyCamera.Parameters[PLCameraInstance.GrabCameraEvents].SetValue(true); // 激活相机事件
- m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
- m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
- m_MyCamera.CameraOpened += Configuration.AcquireContinuous; // 软触发打开
- break;
- }
- }
- if (m_MyCamera == null)
- {
- throw new Exception("没有识别到相机");
- }
- }
- if (!m_MyCamera.IsOpen)
- {
- m_MyCamera.Open();
- m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
- m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
- m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
- }
- IsConnected = m_MyCamera.IsConnected;
- return IsConnected;
- }
- private void M_MyCamera_CameraClosed(object sender, EventArgs e)
- {
- CameraConnectChangedEvent?.Invoke(ID, false);
- }
- private void M_MyCamera_CameraOpened(object sender, EventArgs e)
- {
- CameraConnectChangedEvent?.Invoke(ID, true);
- }
- /// <summary>
- /// 关闭相机
- /// </summary>
- public void CloseDevice()
- {
- if (m_MyCamera != null)
- {
- if (m_MyCamera.IsOpen)
- {
- m_MyCamera.Close();
- m_MyCamera.CameraOpened -= Configuration.AcquireContinuous; // 软触发打开
- m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
- m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
- IsConnected = m_MyCamera.IsConnected;
- m_MyCamera.Dispose();
- }
- }
- }
- /// <summary>
- /// 采集图像
- /// </summary>
- /// <returns></returns>
- public ICogImage Grab()
- {
- Stopwatch sw = Stopwatch.StartNew();
- if (m_MyCamera == null)
- {
- throw new Exception("相机未连接");
- }
- if (!m_MyCamera.IsOpen)
- {
- m_MyCamera.Open();
- m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
- m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
- m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
- }
- if (!m_MyCamera.StreamGrabber.IsGrabbing)
- {
- // Start grabbing.
- m_MyCamera.StreamGrabber.Start();
- }
- bool Succeed = false;
- IGrabResult grabResult = null;
- for (int i = 0; i < 5; i++)
- {
- try
- {
- m_MyCamera.ExecuteSoftwareTrigger();
- // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
- grabResult = m_MyCamera.StreamGrabber.RetrieveResult(1000, TimeoutHandling.ThrowException);
- if (grabResult != null && grabResult.GrabSucceeded)
- {
- ErrorMessage = "";
- Succeed = true;
- break;
- }
- else
- {
- ErrorMessage = grabResult.ErrorDescription;
- }
- }
- catch (Exception ex)
- {
- ErrorMessage = ex.Message;
- m_MyCamera.Close();
- m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
- m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
- m_MyCamera.Open();
- m_MyCamera.Parameters[PLCamera.TriggerSource].SetValue(PLCamera.TriggerSource.Software);
- m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
- m_MyCamera.Parameters[PLCamera.TriggerMode].SetValue(PLCamera.TriggerMode.On);
- IsConnected = m_MyCamera.IsConnected;
- }
- finally
- {
- //m_MyCamera.StreamGrabber.Stop();
- }
- }
- if (!Succeed)
- {
- if (IsConnected)
- {
- IsConnected = false;
- CameraConnectChangedEvent?.Invoke(ID, false);
- }
- return null;
- }
- //m_MyCamera.StreamGrabber.Stop();
- if (IsColorPixelFormat(grabResult.PixelTypeValue))
- {
- Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
- // Lock the bits of the bitmap.
- BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
- converter.OutputPixelFormat = PixelType.BGRA8packed;
- // Place the pointer to the buffer of the bitmap.
- IntPtr ptrBmp = bmpData.Scan0;
- converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
- bitmap.UnlockBits(bmpData);
- CogImage24PlanarColor colorImage = new CogImage24PlanarColor(bitmap);
- Image = colorImage.ScaleImage((int)bitmap.Width, (int)bitmap.Height);
- }
- else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
- {
- byte[] pixelData = grabResult.PixelData as byte[];
- IntPtr pixelPointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
- IntPtr pTemp = IntPtr.Zero;
- Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Undefined;
- UInt32 nSaveImageNeedSize = 0;
- enDstPixelType = Basler.Pylon.PixelType.Mono8;
- nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height * 3;
- if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
- {
- pTemp = pixelPointer;
- }
- else
- {
- // 其他格式Mono转为Mono8
- Basler.Pylon.PixelDataConverter converter = new PixelDataConverter();
- converter.OutputPixelFormat = Basler.Pylon.PixelType.RGB8packed;
- converter.Convert(pTemp, nSaveImageNeedSize, grabResult);
- }
- Image = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
- }
- GC.Collect();
- grabResult.Dispose();
- TotalTime = sw.Elapsed;
- return Image;
- }
- private void InvertColors(IGrabResult result)
- {
- byte pixelSize = 255;
- byte[] data = (byte[])result.PixelData;
- for (long i = 0; i < data.Length; i++)
- {
- data[i] = (byte)((int)pixelSize - (int)data[i]);
- }
- }
- /// <summary>
- /// 转换成ICogImage图像
- /// </summary>
- /// <param name="nHeight"></param>
- /// <param name="nWidth"></param>
- /// <param name="pImageBuf"></param>
- /// <param name="enPixelType"></param>
- /// <returns></returns>
- public ICogImage ConvertToICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, Basler.Pylon.PixelType enPixelType)
- {
- // ch: 显示 || display
- try
- {
- if (enPixelType == Basler.Pylon.PixelType.Mono8)
- {
- CogImage8Root cogImage8Root = new CogImage8Root();
- cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
- CogImage8Grey cogImage8Grey = new CogImage8Grey();
- cogImage8Grey.SetRoot(cogImage8Root);
- return cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
- }
- else
- {
- CogImage8Root image0 = new CogImage8Root();
- IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
- image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
- CogImage8Root image1 = new CogImage8Root();
- IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + m_nRowStep);
- image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
- CogImage8Root image2 = new CogImage8Root();
- IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + m_nRowStep * 2);
- image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
- CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
- colorImage.SetRoots(image0, image1, image2);
- return colorImage.ScaleImage((int)nWidth, (int)nHeight);
- }
- }
- catch (System.Exception)
- {
- return null;
- }
- }
- /// <summary>
- /// 开始采集图像
- /// </summary>
- public void StartGrabbing()
- {
- if (m_MyCamera == null)
- {
- throw new Exception("相机未连接");
- }
- if (!m_MyCamera.IsOpen)
- {
- throw new Exception("相机未打开");
- }
- m_MyCamera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
- //m_MyCamera.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
- if (IsGrabbing)
- return;
- if (!m_MyCamera.StreamGrabber.IsGrabbing)
- {
- // Start grabbing.
- m_MyCamera.StreamGrabber.Start();
- }
- IsGrabbing = true;
- m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
- m_hReceiveThread.Start();
- }
- /// <summary>
- /// 停止采集图像
- /// </summary>
- public void StopGrabbing()
- {
- try
- {
- //m_MyCamera.StreamGrabber.Stop();
- IsGrabbing = false;
- Thread.Sleep(1000);
- if (m_hReceiveThread != null)
- {
- m_hReceiveThread.Abort();
- m_hReceiveThread = null;
- }
- if (m_MyCamera != null && m_MyCamera.StreamGrabber.IsGrabbing)
- {
- m_MyCamera.StreamGrabber.Stop();
- }
- }
- catch (Exception)
- {
- }
- }
- /// <summary>
- /// 设置曝光时间
- /// </summary>
- /// <param name="ExposureTime"></param>
- /// <returns></returns>
- public bool SetExposureTime(float ExposureTime)
- {
- if (m_MyCamera == null)
- {
- return false;
- }
- if (m_MyCamera.Parameters.Contains(PLCamera.ExposureTimeAbs))
- {
- m_MyCamera.Parameters[PLCamera.ExposureTimeAbs].SetValue(ExposureTime);
- }
- else
- m_MyCamera.Parameters[PLCamera.ExposureTime].SetValue(ExposureTime);
- return true;
- }
- /// <summary>
- /// 获取曝光时间
- /// </summary>
- /// <returns></returns>
- public float GetExposureTime()
- {
- if (m_MyCamera == null)
- {
- return 0;
- }
- if (m_MyCamera.Parameters.Contains(PLCamera.ExposureTimeAbs))
- {
- return (float)m_MyCamera.Parameters[PLCamera.ExposureTimeAbs].GetValue();
- }
- else
- return (float)m_MyCamera.Parameters[PLCamera.ExposureTime].GetValue();
- }
- /// <summary>
- /// 设置增益
- /// </summary>
- /// <param name="Gain"></param>
- /// <returns></returns>
- public bool SetGain(float Gain)
- {
- if (m_MyCamera == null)
- {
- return false;
- }
- if (m_MyCamera.Parameters.Contains(PLCamera.Gain))
- {
- m_MyCamera.Parameters[PLCamera.Gain].SetValue(Gain);
- }
- else if (m_MyCamera.Parameters.Contains(PLCamera.GainRaw))
- {
- m_MyCamera.Parameters[PLCamera.GainRaw].SetValue((int)Gain);
- }
- else if (m_MyCamera.Parameters.Contains(PLCamera.GainAbs))
- {
- m_MyCamera.Parameters[PLCamera.GainAbs].SetValue(Gain);
- }
- return true;
- }
- /// <summary>
- /// 获取增益
- /// </summary>
- /// <returns></returns>
- public float GetGain()
- {
- if (m_MyCamera.Parameters.Contains(PLCamera.Gain))
- {
- return (float)m_MyCamera.Parameters[PLCamera.Gain].GetValue();
- }
- else
- return (float)m_MyCamera.Parameters[PLCamera.GainAbs].GetValue();
- }
- private void GetStreamThreadProc()
- {
- while (IsGrabbing)
- {
- Stopwatch sw = Stopwatch.StartNew();
- try
- {
- if (!m_MyCamera.IsConnected)
- {
- m_MyCamera.Close();
- m_MyCamera.CameraOpened -= M_MyCamera_CameraOpened;
- m_MyCamera.CameraClosed -= M_MyCamera_CameraClosed;
- m_MyCamera = new Basler.Pylon.Camera(CameraInfo);
- m_MyCamera.CameraOpened += M_MyCamera_CameraOpened;
- m_MyCamera.CameraClosed += M_MyCamera_CameraClosed;
- }
- if (!m_MyCamera.IsOpen)
- {
- m_MyCamera.Open();
- IsConnected = m_MyCamera.IsConnected;
- }
- m_MyCamera.ExecuteSoftwareTrigger();
- // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
- IGrabResult grabResult = m_MyCamera.StreamGrabber.RetrieveResult(1000, TimeoutHandling.ThrowException);
- using (grabResult)
- {
- // Image grabbed successfully?
- if (grabResult != null && grabResult.GrabSucceeded)
- {
- ErrorMessage = "";
- byte[] pixelData = grabResult.PixelData as byte[];
- IntPtr pixelPointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixelData, 0);
- IntPtr pTemp = IntPtr.Zero;
- Basler.Pylon.PixelType enDstPixelType = Basler.Pylon.PixelType.Undefined;
- UInt32 nSaveImageNeedSize = 0;
- if (IsColorPixelFormat(grabResult.PixelTypeValue))
- {
- Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
- // Lock the bits of the bitmap.
- BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
- converter.OutputPixelFormat = PixelType.BGRA8packed;
- // Place the pointer to the buffer of the bitmap.
- IntPtr ptrBmp = bmpData.Scan0;
- converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
- bitmap.UnlockBits(bmpData);
- CogImage24PlanarColor colorImage = new CogImage24PlanarColor(bitmap);
- Image = colorImage.ScaleImage((int)bitmap.Width, (int)bitmap.Height);
- }
- else if (IsMonoPixelFormat(grabResult.PixelTypeValue))
- {
- enDstPixelType = Basler.Pylon.PixelType.Mono8;
- nSaveImageNeedSize = (uint)grabResult.Width * (uint)grabResult.Height * 3;
- if (grabResult.PixelTypeValue == Basler.Pylon.PixelType.Mono8)
- {
- pTemp = pixelPointer;
- }
- else
- {
- // 其他格式Mono转为Mono8
- Basler.Pylon.PixelDataConverter converter = new PixelDataConverter();
- converter.OutputPixelFormat = Basler.Pylon.PixelType.RGB8packed;
- converter.Convert(pTemp, nSaveImageNeedSize, grabResult);
- }
- Image = ConvertToICogImage((uint)grabResult.Height, (uint)grabResult.Width, pTemp, enDstPixelType);
- }
- TotalTime = sw.Elapsed;
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- else
- {
- TotalTime = sw.Elapsed;
- ErrorMessage = grabResult.ErrorDescription;
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- }
- }
- catch (Exception ex)
- {
- TotalTime = sw.Elapsed;
- ImageCallbackEvent?.Invoke(Image, TotalTime, ex.Message);
- }
- Thread.Sleep(10);
- GC.Collect();
- }
- IsGrabbing = false;
- }
- /// <summary>
- /// 图像是否为彩色
- /// </summary>
- /// <param name="enType"></param>
- /// <returns></returns>
- private bool IsColorPixelFormat(Basler.Pylon.PixelType enType)
- {
- switch (enType)
- {
- case Basler.Pylon.PixelType.RGB8packed:
- case Basler.Pylon.PixelType.BGR8packed:
- case Basler.Pylon.PixelType.RGBA8packed:
- case Basler.Pylon.PixelType.BGRA8packed:
- case Basler.Pylon.PixelType.YUV422packed:
- case Basler.Pylon.PixelType.YUV422_YUYV_Packed:
- case Basler.Pylon.PixelType.BayerGR8:
- case Basler.Pylon.PixelType.BayerRG8:
- case Basler.Pylon.PixelType.BayerGB8:
- case Basler.Pylon.PixelType.BayerBG8:
- case Basler.Pylon.PixelType.BayerGB10:
- case Basler.Pylon.PixelType.BayerGB10pp:
- case Basler.Pylon.PixelType.BayerBG10:
- case Basler.Pylon.PixelType.BayerBG10pp:
- case Basler.Pylon.PixelType.BayerRG10:
- case Basler.Pylon.PixelType.BayerRG10pp:
- case Basler.Pylon.PixelType.BayerGR10:
- case Basler.Pylon.PixelType.BayerGR10pp:
- case Basler.Pylon.PixelType.BayerGB12:
- case Basler.Pylon.PixelType.BayerGB12p:
- case Basler.Pylon.PixelType.BayerBG12:
- case Basler.Pylon.PixelType.BayerBG12Packed:
- case Basler.Pylon.PixelType.BayerRG12:
- case Basler.Pylon.PixelType.BayerRG12Packed:
- case Basler.Pylon.PixelType.BayerGR12:
- case Basler.Pylon.PixelType.BayerGR12Packed:
- return true;
- default:
- return false;
- }
- }
- /// <summary>
- /// 图像是否为Mono格式
- /// </summary>
- /// <param name="enType"></param>
- /// <returns></returns>
- private bool IsMonoPixelFormat(Basler.Pylon.PixelType enType)
- {
- switch (enType)
- {
- case Basler.Pylon.PixelType.Mono8:
- case Basler.Pylon.PixelType.Mono10:
- case Basler.Pylon.PixelType.Mono10packed:
- case Basler.Pylon.PixelType.Mono12:
- case Basler.Pylon.PixelType.Mono12packed:
- return true;
- default:
- return false;
- }
- }
- /// <summary>
- /// 将相机抓取到的图像转换成Bitmap位图
- /// </summary>
- /// <param name="grabResult"></param>
- /// <returns></returns>
- //Bitmap GrabResult2Bmp(IGrabResult grabResult)
- //{
- // Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb); // 转bit图
- // BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
- // PixelDataConverter converter = new PixelDataConverter();
- // converter.OutputPixelFormat = PixelType.BGRA8packed;
- // IntPtr ptrBmp = bmpData.Scan0;
- // converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
- // bitmap.UnlockBits(bmpData);
- // return (Bitmap)bitmap.Clone();
- //}
- #endregion
- #region 属性通知
- /// <summary>
- /// Occurs when a property value changes.
- /// </summary>
- public event PropertyChangedEventHandler PropertyChanged;
- /// <summary>
- /// Checks if a property already matches a desired value. Sets the property and
- /// notifies listeners only when necessary.
- /// </summary>
- /// <typeparam name="T">Type of the property.</typeparam>
- /// <param name="storage">Reference to a property with both getter and setter.</param>
- /// <param name="value">Desired value for the property.</param>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers that
- /// support CallerMemberName.</param>
- /// <returns>True if the value was changed, false if the existing value matched the
- /// desired value.</returns>
- protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
- {
- if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
- storage = value;
- RaisePropertyChanged(propertyName);
- return true;
- }
- /// <summary>
- /// Checks if a property already matches a desired value. Sets the property and
- /// notifies listeners only when necessary.
- /// </summary>
- /// <typeparam name="T">Type of the property.</typeparam>
- /// <param name="storage">Reference to a property with both getter and setter.</param>
- /// <param name="value">Desired value for the property.</param>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers that
- /// support CallerMemberName.</param>
- /// <param name="onChanged">Action that is called after the property value has been changed.</param>
- /// <returns>True if the value was changed, false if the existing value matched the
- /// desired value.</returns>
- protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
- {
- if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
- storage = value;
- onChanged?.Invoke();
- RaisePropertyChanged(propertyName);
- return true;
- }
- /// <summary>
- /// Raises this object's PropertyChanged event.
- /// </summary>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers
- /// that support <see cref="CallerMemberNameAttribute"/>.</param>
- protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
- {
- OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
- }
- /// <summary>
- /// Raises this object's PropertyChanged event.
- /// </summary>
- /// <param name="args">The PropertyChangedEventArgs</param>
- protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
- {
- PropertyChanged?.Invoke(this, args);
- }
- #endregion
- }
- }
|