| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075 |
- using Cognex.VisionPro;
- using GxIAPINET;
- using MathNet.Numerics.LinearAlgebra;
- using Microsoft.Win32;
- using NPOI.Util;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Threading.Tasks;
- using TeamAAS_VP.Core.GalaxyMethod;
- using TeamAAS_VP.Enums;
- using TeamAAS_VP.Interfaces;
- using TeamAAS_VP.Models;
- using TeamAAS_VP.Resources.Languages;
- namespace TeamAAS_VP.Core.Cameras
- {
- public class GalaxyCamera : CameraBase, ICamera, INotifyPropertyChanged
- {
- #region 字段
- private Thread m_hReceiveThread;
- static IGXFactory m_objIGXFactory = null; //Factory对像
- IGXDevice m_objIGXDevice = null; //设备对像
- IGXStream m_objIGXStream = null; //流对像
- static List<IGXDeviceInfo> m_listIGXDeviceInfo = new List<IGXDeviceInfo>(); //设备信息列表
- IGXFeatureControl m_objIGXFeatureControl = null; //远端设备属性控制器对像
- IGXFeatureControl m_objIGXStreamFeatureControl = null; //流层属性控制器对象
- IntPtr m_pOutBuffer = IntPtr.Zero; //图像质量提升或图像格式转换输出Buffer
- IntPtr m_pBitmapInfo = IntPtr.Zero;
- bool m_bIsColor = false; ///<是否支持彩色相机
- byte[] m_byMonoBuffer = null; ///<黑白相机buffer
- byte[] m_byColorBuffer = null; ///<彩色相机buffer
- int m_nWidth = 0; ///<图像宽度
- int m_nHeight = 0; ///<图像高度
- IGXImageFormatConvert m_objImageFormatConvert = null; ///<IGXImageFormatConvert对象,仅供图像格式转换使用
- CWin32Bitmaps.BITMAPINFO m_objBitmapInfo = new CWin32Bitmaps.BITMAPINFO();
- #endregion
- #region 属性
- public string Name { get; private set; }
- public Guid ID { get; private set; }
- public int Index { get; set; }
- public CameraBrand CameraBrand { get => CameraBrand.Galaxy; }
- public bool IsFindByIp { get; private set; }
- public string ManufacturerName { get; private set; }
- public string ModelName { get; private set; }
- public string SerialNumber { get; private set; }
- public string CameraIp { get; private set; }
- public CameraType CameraType { 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 TimeSpan TotalTime { get; private set; }
- public string ErrorMessage { get; private set; }
- public uint ImageWidth { get; private set; }
- public uint ImageHeight { get; private set; }
- private bool IsHaveCamera = false;
- #endregion
- #region 事件
- public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
- public event Action<Guid, bool> CameraConnectChangedEvent;
- #endregion
- public GalaxyCamera(Guid id, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
- {
- ID = id;
- Name = serialNumber;
- Index = index;
- CameraIp = cameraip;
- SerialNumber = serialNumber;
- IsFindByIp = isFindByIp;
- var list = GetDevices();
- foreach (var device in list)
- {
- if (device.CameraType== CameraType.GIGE)
- {
- if (IsFindByIp)
- {
- if (device.CameraIp == CameraIp)
- {
- IsHaveCamera = true;
- ManufacturerName = device.ManufacturerName;
- ModelName = device.Model;
- SerialNumber = device.SerialNumber;
- CameraType = CameraType.GIGE;
- break;
- }
- }
- else
- {
- if (device.SerialNumber == serialNumber)
- {
- IsHaveCamera = true;
- ManufacturerName = device.ManufacturerName;
- ModelName = device.Model;
- SerialNumber = device.SerialNumber;
- CameraType = CameraType.GIGE;
- break;
- }
- }
- }
- else
- {
- if (device.SerialNumber == serialNumber)
- {
- IsHaveCamera = true;
- ManufacturerName = device.ManufacturerName;
- ModelName = device.Model;
- SerialNumber = device.SerialNumber;
- CameraType = CameraType.GIGE;
- break;
- }
- }
- }
- IsConnected = false;
- }
- #region 方法
- /// <summary>
- /// 获取设备
- /// </summary>
- /// <returns></returns>
- public static CameraInfo[] GetDevices()
- {
- m_objIGXFactory = IGXFactory.GetInstance();
- m_objIGXFactory.Init();//相机初始化
- List<CameraInfo> cameras = new List<CameraInfo>();
- if (!CheckSoftwareInstalled().isInstalled)
- {
- LogHelper.WriteLogInfo(Lang.未安装GalaxyViewer);
- return cameras.ToArray();
- }
- m_listIGXDeviceInfo.Clear();
- if (null != m_objIGXFactory)
- {
- m_objIGXFactory.UpdateAllDeviceList(200, m_listIGXDeviceInfo);
- }
- // 判断当前连接设备个数
- if (m_listIGXDeviceInfo.Count <= 0)
- {
- LogHelper.WriteLogInfo(Lang.未检测到设备请确保设备正常连接然后重启程序);
- return cameras.ToArray();
- }
- for (int i = 0; i < m_listIGXDeviceInfo.Count; i++)
- {
- var deviceType = m_listIGXDeviceInfo[i].GetDeviceClass();
- if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_GEV)
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = m_listIGXDeviceInfo[i].GetDisplayName(),
- CameraBrand = CameraBrand.Galaxy,
- CameraType = CameraType.GIGE,
- ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
- Model = m_listIGXDeviceInfo[i].GetModelName(),
- SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
- CameraIp = m_listIGXDeviceInfo[i].GetIP(),
- IsFindByIp=true,
- });
- }
- else if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_USB2 || deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_U3V)
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = m_listIGXDeviceInfo[i].GetDisplayName(),
- CameraBrand = CameraBrand.Galaxy,
- CameraType = CameraType.USB,
- ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
- Model = m_listIGXDeviceInfo[i].GetModelName(),
- SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
- CameraIp = "",
- });
- }
- else if (deviceType == GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_UNKNOWN)
- {
- cameras.Add(new Models.CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = m_listIGXDeviceInfo[i].GetDisplayName(),
- CameraBrand = CameraBrand.Galaxy,
- CameraType = CameraType.Unknown,
- ManufacturerName = m_listIGXDeviceInfo[i].GetVendorName(),
- Model = m_listIGXDeviceInfo[i].GetModelName(),
- SerialNumber = m_listIGXDeviceInfo[i].GetSN(),
- CameraIp = "",
- });
- }
- }
- return cameras.ToArray();
- }
- /// <summary>
- /// 检查相机软件是否安装
- /// </summary>
- /// <returns></returns>
- public static (bool isInstalled, string version) CheckSoftwareInstalled()
- {
- string softwareName = "Galaxy";
- string softwareVersion = "2.4.2504";
- 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("DisplayName")?.ToString();
- var match = Regex.Match(version, @"\d+(?:\.\d+)+");
- if (match.Success)
- {
- version = match.Value;
- }
- else
- {
- continue;
- }
- Version v1 = new Version(version);
- Version v2 = new Version(softwareVersion);
- if (v1 >= v2)
- {
- return (true, version);
- }
- else
- {
- return (false, version);
- }
- }
- }
- }
- }
- }
- return (false, "");
- }
- public void CloseDevice()
- {
- EnterOperation();
- try
- {
- try
- {
- if (null != m_objIGXFeatureControl)
- {
- m_objIGXFeatureControl.GetCommandFeature("AcquisitionStop").Execute();
- m_objIGXFeatureControl = null;
- }
- //停止流通道、注销采集回调和关闭流
- if (null != m_objIGXStream)
- {
- m_objIGXStream.StopGrab();
- //注销采集回调函数
- m_objIGXStream.UnregisterCaptureCallback();
- m_objIGXStream.Close();
- m_objIGXStream = null;
- m_objIGXStreamFeatureControl = null;
- }
- //关闭设备
- if (null != m_objIGXDevice)
- {
- m_objIGXDevice.Close();
- m_objIGXDevice = null;
- }
- //反初始化
- if (null != m_objIGXFactory)
- {
- m_objIGXFactory.Uninit();
- }
- }
- catch (Exception)
- {
- }
- ReleaseBuffer();
- }
- finally
- {
- ExitOperation();
- }
- }
- public float GetExposureTime()
- {
- EnterOperation();
- try
- {
- if (null != m_objIGXFeatureControl)
- {
- double dCurShuter = m_objIGXFeatureControl.GetFloatFeature("ExposureTime").GetValue();
- return (float)dCurShuter;
- }
- else
- { return 0; }
- }
- finally
- {
- ExitOperation();
- }
- }
- public float GetGain()
- {
- EnterOperation();
- try
- {
- if (null != m_objIGXFeatureControl)
- {
- double dCurGain = m_objIGXFeatureControl.GetFloatFeature("Gain").GetValue();
- return (float)dCurGain;
- }
- else
- { return 0; }
- }
- finally
- {
- ExitOperation();
- }
- }
- public ICogImage Grab()
- {
- EnterOperation();
- try
- {
- IImageData objIImageData = null;
- Stopwatch sw = Stopwatch.StartNew();
- for (int j = 0; j < 5; j++)
- {
- try
- {
- if (null == m_objIGXDevice)
- {
- OpenDevice();
- }
- //开启采集流通道
- if (null != m_objIGXStream)
- {
- m_objIGXStream.StartGrab();
- }
- //发送开采命令
- if (null != m_objIGXFeatureControl)
- {
- m_objIGXFeatureControl.GetCommandFeature("AcquisitionStart").Execute();
- }
- objIImageData = m_objIGXStream.GetImageNoThrow(500);
- //===================================
- GX_VALID_BIT_LIST emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
- if (null != objIImageData)
- {
- emValidBits = GetBestValudBit(objIImageData.GetPixelFormat());
- if (GX_FRAME_STATUS_LIST.GX_FRAME_STATUS_SUCCESS == objIImageData.GetStatus())
- {
- if (m_bIsColor)
- {
- IntPtr pRGB24Buffer = IntPtr.Zero;
- if (objIImageData.GetPixelFormat() == GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8)
- {
- byte[] byColorBufferTmp = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
- Marshal.Copy(objIImageData.GetBuffer(), byColorBufferTmp, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
- pRGB24Buffer = objIImageData.GetBuffer();
- //BGR8格式需要翻转数据后显示
- for (int i = 0; i < m_nHeight; i++)
- {
- Buffer.BlockCopy(byColorBufferTmp, (m_nHeight - i - 1) * m_nWidth * 3, m_byColorBuffer, i * m_nWidth * 3, m_nWidth * 3);
- }
- }
- else
- {
- // 设置目标像素格式
- m_objImageFormatConvert.SetDstFormat(GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8);
- // 获取目标像素格式Buffer大小
- UInt64 i64DstBufferize = m_objImageFormatConvert.GetBufferSizeForConversion(objIImageData);
- // 设置目标有效位数
- m_objImageFormatConvert.SetValidBits(emValidBits);
- // 进行图像格式转换
- m_objImageFormatConvert.Convert(objIImageData, m_pOutBuffer, i64DstBufferize, true);
- Marshal.Copy(m_pOutBuffer, m_byColorBuffer, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
- pRGB24Buffer = m_pOutBuffer;
- }
- Image = ConvertImage((uint)m_nWidth, (uint)m_nHeight, pRGB24Buffer, GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8);
- }
- else
- {
- IntPtr pRaw8Buffer = IntPtr.Zero;
- if (__IsPixelFormat8(objIImageData.GetPixelFormat()))
- {
- byte[] byMonoBufferTmp = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
- Marshal.Copy(objIImageData.GetBuffer(), byMonoBufferTmp, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
- pRaw8Buffer = objIImageData.GetBuffer();
- // 黑白相机需要翻转数据后显示
- for (int i = 0; i < m_nHeight; i++)
- {
- Buffer.BlockCopy(byMonoBufferTmp, (m_nHeight - i - 1) * m_nWidth, m_byMonoBuffer, i * m_nWidth, m_nWidth);
- }
- }
- else
- {
- // 设置目标像素格式
- m_objImageFormatConvert.SetDstFormat(GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8);
- // 获取目标像素格式Buffer大小
- UInt64 i64DstBufferize = m_objImageFormatConvert.GetBufferSizeForConversion(objIImageData);
- // 设置目标有效位数
- m_objImageFormatConvert.SetValidBits(emValidBits);
- // 进行图像格式转换
- m_objImageFormatConvert.Convert(objIImageData, m_pOutBuffer, i64DstBufferize, true);
- Marshal.Copy(m_pOutBuffer, m_byMonoBuffer, 0, __GetStride(m_nWidth, m_bIsColor) * m_nHeight);
- pRaw8Buffer = m_pOutBuffer;
- }
- Image = ConvertImage((uint)m_nWidth, (uint)m_nHeight, pRaw8Buffer, GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8);
- }
- }
- }
- if (Image != null)
- {
- ErrorMessage = "";
- TotalTime = sw.Elapsed;
- return Image;
- }
- }
- catch (Exception ex)
- {
- CloseDevice();
- OpenDevice();
- ErrorMessage = ex.Message;
- }
- finally
- {
- if (null != objIImageData)
- {
- //用完之后释放资源
- objIImageData.Destroy();
- }
- }
- }
- if (IsConnected)
- {
- IsConnected = false;
- CameraConnectChangedEvent?.Invoke(ID, false);
- }
- return null;
- }
- finally
- {
- ExitOperation();
- }
- }
- public bool OpenDevice()
- {
- EnterOperation();
- try
- {
- IsConnected = false;
- var list = GetDevices();
- foreach (var device in list)
- {
- if (device.CameraType == CameraType.GIGE)
- {
- if (IsFindByIp)
- {
- if (device.CameraIp == CameraIp)
- {
- IsHaveCamera = true;
- ManufacturerName = device.ManufacturerName;
- ModelName = device.Model;
- SerialNumber = device.SerialNumber;
- CameraType = CameraType.GIGE;
- break;
- }
- }
- else
- {
- if (device.SerialNumber == SerialNumber)
- {
- IsHaveCamera = true;
- ManufacturerName = device.ManufacturerName;
- ModelName = device.Model;
- SerialNumber = device.SerialNumber;
- CameraType = CameraType.GIGE;
- break;
- }
- }
- }
- else
- {
- if (device.SerialNumber == SerialNumber)
- {
- IsHaveCamera = true;
- ManufacturerName = device.ManufacturerName;
- ModelName = device.Model;
- SerialNumber = device.SerialNumber;
- CameraType = CameraType.GIGE;
- break;
- }
- }
- }
- if (!IsHaveCamera)
- {
- //throw new Exception("没有发现相机");
- return false;
- }
- // 如果设备已经打开则关闭,保证相机在初始化出错情况下能再次打开
- if (null != m_objIGXDevice)
- {
- m_objIGXDevice.Close();
- m_objIGXDevice = null;
- }
- //打开设备
- m_objIGXDevice = m_objIGXFactory.OpenDeviceBySN(SerialNumber, GxIAPINET.GX_ACCESS_MODE.GX_ACCESS_EXCLUSIVE);
- m_objIGXFeatureControl = m_objIGXDevice.GetRemoteFeatureControl();
- //打开流
- if (null != m_objIGXDevice)
- {
- m_objIGXStream = m_objIGXDevice.OpenStream(0);
- m_objIGXStreamFeatureControl = m_objIGXStream.GetFeatureControl();
- }
- // 建议用户在打开网络相机之后,根据当前网络环境设置相机的流通道包长值,
- // 以提高网络相机的采集性能,设置方法参考以下代码。
- GX_DEVICE_CLASS_LIST objDeviceClass = m_objIGXDevice.GetDeviceInfo().GetDeviceClass();
- if (GX_DEVICE_CLASS_LIST.GX_DEVICE_CLASS_GEV == objDeviceClass)
- {
- // 判断设备是否支持流通道数据包功能
- if (true == m_objIGXFeatureControl.IsImplemented("GevSCPSPacketSize"))
- {
- // 获取当前网络环境的最优包长值
- uint nPacketSize = m_objIGXStream.GetOptimalPacketSize();
- // 将最优包长值设置为当前设备的流通道包长值
- m_objIGXFeatureControl.GetIntFeature("GevSCPSPacketSize").SetValue(nPacketSize);
- }
- }
- //初始化相机参数
- if (null != m_objIGXFeatureControl)
- {
- //设置采集模式连续采集
- m_objIGXFeatureControl.GetEnumFeature("AcquisitionMode").SetValue("Continuous");
- //设置触发模式为关
- m_objIGXFeatureControl.GetEnumFeature("TriggerMode").SetValue("Off");
- }
- ReleaseBuffer();
- GxBitmap();
- if (null != m_objIGXStreamFeatureControl)
- {
- try
- {
- //设置流层Buffer处理模式为OldestFirst
- m_objIGXStreamFeatureControl.GetEnumFeature("StreamBufferHandlingMode").SetValue("OldestFirst");
- }
- catch (Exception)
- {
- }
- }
- if (!IsConnected)
- {
- CameraConnectChangedEvent?.Invoke(ID, true);
- }
- IsConnected = true;
- return IsConnected;
- }
- finally
- {
- ExitOperation();
- }
- }
- /// <summary>
- /// 打开相机异步
- /// </summary>
- /// <returns></returns>
- public Task<bool> OpenDeviceAsync()
- {
- return Task.Run(() =>
- {
- return OpenDevice();
- });
- }
- public bool SetExposureTime(float ExposureTime)
- {
- EnterOperation();
- try
- {
- if (null == m_objIGXFeatureControl)
- return false;
- if (GetExposureTime() != ExposureTime)
- {
- bool success = false;
- for (int i = 0; i < 5; i++)
- {
- m_objIGXFeatureControl.GetFloatFeature("ExposureTime").SetValue(ExposureTime);
- success = true;
- }
- return success;
- }
- return true;
- }
- finally
- {
- ExitOperation();
- }
- }
- public bool SetGain(float Gain)
- {
- EnterOperation();
- try
- {
- if (null == m_objIGXFeatureControl)
- return false;
- if (GetGain() != Gain)
- {
- bool success = false;
- for (int i = 0; i < 5; i++)
- {
- m_objIGXFeatureControl.GetFloatFeature("Gain").SetValue(Gain);
- success = true;
- }
- return success;
- }
- return true;
- }
- finally
- {
- ExitOperation();
- }
- }
- public void StartGrabbing()
- {
- lock (_stateLock)
- {
- if (IsGrabbing)
- return;
- IsGrabbing = true;
- }
- m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
- m_hReceiveThread.Start();
- }
- public void StopGrabbing()
- {
- try
- {
- lock (_stateLock)
- {
- IsGrabbing = false;
- }
- Thread.Sleep(1000);
- if (m_hReceiveThread != null)
- {
- m_hReceiveThread.Abort();
- m_hReceiveThread = null;
- }
- }
- catch (Exception)
- {
- }
- }
- private void GetStreamThreadProc()
- {
- while (IsGrabbing)
- {
- try
- {
- Grab();
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- catch (Exception)
- {
- }
- Thread.Sleep(10);
- }
- IsGrabbing = false;
- }
- #endregion
- #region method
- /// <summary>
- /// 初始化设备对象
- /// </summary>
- /// <param name="objIGXDevice">设备对象</param>
- public void GxBitmap()
- {
- // 初始化图像格式转换对象
- m_objImageFormatConvert = m_objIGXFactory.CreateImageFormatConvert();
- if (null != m_objIGXDevice)
- {
- m_nWidth = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("Width").GetValue();
- m_nHeight = (int)m_objIGXDevice.GetRemoteFeatureControl().GetIntFeature("Height").GetValue();
- ImageWidth = (uint)m_nWidth;
- ImageHeight = (uint)m_nHeight;
- //获取是否为彩色相机
- IsSupportColor(ref m_bIsColor);
- }
- //申请用于缓存图像数据的buffer
- m_byMonoBuffer = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
- m_byColorBuffer = new byte[__GetStride(m_nWidth, m_bIsColor) * m_nHeight];
- m_pOutBuffer = Marshal.AllocCoTaskMem(__GetStride(m_nWidth, m_bIsColor) * m_nHeight);
- if (m_bIsColor)
- {
- m_objBitmapInfo.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(CWin32Bitmaps.BITMAPINFOHEADER));
- m_objBitmapInfo.bmiHeader.biWidth = m_nWidth;
- m_objBitmapInfo.bmiHeader.biHeight = m_nHeight;
- m_objBitmapInfo.bmiHeader.biPlanes = 1;
- m_objBitmapInfo.bmiHeader.biBitCount = 24;
- m_objBitmapInfo.bmiHeader.biCompression = 0;
- m_objBitmapInfo.bmiHeader.biSizeImage = 0;
- m_objBitmapInfo.bmiHeader.biXPelsPerMeter = 0;
- m_objBitmapInfo.bmiHeader.biYPelsPerMeter = 0;
- m_objBitmapInfo.bmiHeader.biClrUsed = 0;
- m_objBitmapInfo.bmiHeader.biClrImportant = 0;
- }
- else
- {
- m_objBitmapInfo.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(CWin32Bitmaps.BITMAPINFOHEADER));
- m_objBitmapInfo.bmiHeader.biWidth = m_nWidth;
- m_objBitmapInfo.bmiHeader.biHeight = m_nHeight;
- m_objBitmapInfo.bmiHeader.biPlanes = 1;
- m_objBitmapInfo.bmiHeader.biBitCount = 8;
- m_objBitmapInfo.bmiHeader.biCompression = 0;
- m_objBitmapInfo.bmiHeader.biSizeImage = 0;
- m_objBitmapInfo.bmiHeader.biXPelsPerMeter = 0;
- m_objBitmapInfo.bmiHeader.biYPelsPerMeter = 0;
- m_objBitmapInfo.bmiHeader.biClrUsed = 0;
- m_objBitmapInfo.bmiHeader.biClrImportant = 0;
- m_objBitmapInfo.bmiColors = new CWin32Bitmaps.RGBQUAD[256];
- // 黑白图像需要初始化调色板
- for (int i = 0; i < 256; i++)
- {
- m_objBitmapInfo.bmiColors[i].rgbBlue = (byte)i;
- m_objBitmapInfo.bmiColors[i].rgbGreen = (byte)i;
- m_objBitmapInfo.bmiColors[i].rgbRed = (byte)i;
- m_objBitmapInfo.bmiColors[i].rgbReserved = 0;
- }
- }
- m_pBitmapInfo = Marshal.AllocHGlobal(2048);
- Marshal.StructureToPtr(m_objBitmapInfo, m_pBitmapInfo, false);
- }
- /// <summary>
- /// 释放buffer
- /// </summary>
- public void ReleaseBuffer()
- {
- // 释放输出Buffer内存
- if (m_pOutBuffer != IntPtr.Zero)
- {
- Marshal.FreeCoTaskMem(m_pOutBuffer);
- m_pOutBuffer = IntPtr.Zero;
- }
- if (m_pBitmapInfo != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(m_pBitmapInfo);
- m_pBitmapInfo = IntPtr.Zero;
- }
- }
- /// <summary>
- /// 是否支持彩色
- /// </summary>
- /// <param name="bIsColorFilter">是否支持彩色</param>
- public void IsSupportColor(ref bool bIsColorFilter)
- {
- bool bIsImplemented = false;
- bool bIsMono = false;
- string strPixelFormat = "";
- uint nPixelFormatValue = 0;
- strPixelFormat = m_objIGXDevice.GetRemoteFeatureControl().GetEnumFeature("PixelFormat").GetValue();
- if (0 == string.Compare(strPixelFormat, 0, "Mono", 0, 4))
- {
- bIsMono = true;
- }
- else
- {
- bIsMono = false;
- }
- // 通过当前像素格式判断是否为彩色相机
- CDecide.GetConvertPixelFormat(strPixelFormat, ref nPixelFormatValue);
- bIsImplemented = CDecide.GetIsGray(nPixelFormatValue);
- if ((!bIsMono) && (!bIsImplemented))
- {
- bIsColorFilter = true;
- }
- else
- {
- bIsColorFilter = false;
- }
- }
- /// <summary>
- /// 计算宽度所占的字节数
- /// </summary>
- /// <param name="nWidth">图像宽度</param>
- /// <param name="bIsColor">是否是彩色相机</param>
- /// <returns>图像一行所占的字节数</returns>
- private int __GetStride(int nWidth, bool bIsColor)
- {
- return bIsColor ? nWidth * 3 : nWidth;
- }
- /// <summary>
- /// 通过GX_PIXEL_FORMAT_ENTRY获取最优Bit位
- /// </summary>
- /// <param name="em">图像数据格式</param>
- /// <returns>最优Bit位</returns>
- public GX_VALID_BIT_LIST GetBestValudBit(GX_PIXEL_FORMAT_ENTRY emPixelFormatEntry)
- {
- GX_VALID_BIT_LIST emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
- switch (emPixelFormatEntry)
- {
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_RGB8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BGR8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_R8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_G8:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_B8:
- {
- emValidBits = GX_VALID_BIT_LIST.GX_BIT_0_7;
- break;
- }
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO10_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG10_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB10_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR10_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG10_PACKED:
- {
- emValidBits = GX_VALID_BIT_LIST.GX_BIT_2_9;
- break;
- }
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO12_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG12_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB12_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR12_PACKED:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG12_PACKED:
- {
- emValidBits = GX_VALID_BIT_LIST.GX_BIT_4_11;
- break;
- }
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG14:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB14:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG14_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB14_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR14_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG14_P:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO14_P:
- {
- emValidBits = GX_VALID_BIT_LIST.GX_BIT_6_13;
- break;
- }
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO16:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GR16:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_RG16:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_GB16:
- case GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_BAYER_BG16:
- {
- emValidBits = GX_VALID_BIT_LIST.GX_BIT_8_15;
- break;
- }
- default:
- break;
- }
- return emValidBits;
- }
- /// <summary>
- /// 判断PixelFormat是否为8位
- /// </summary>
- /// <param name="emPixelFormatEntry">图像数据格式</param>
- /// <returns>true为8为数据,false为非8位数据</returns>
- private bool __IsPixelFormat8(GX_PIXEL_FORMAT_ENTRY emPixelFormatEntry)
- {
- const uint PIXEL_FORMATE_BIT = 0x00FF0000; //用于与当前的数据格式进行与运算得到当前的数据位数
- const uint GX_PIXEL_8BIT = 0x00080000; //8位数据图像格式
- bool bIsPixelFormat8 = false;
- uint uiPixelFormatEntry = (uint)emPixelFormatEntry;
- if ((uiPixelFormatEntry & PIXEL_FORMATE_BIT) == GX_PIXEL_8BIT)
- {
- bIsPixelFormat8 = true;
- }
- return bIsPixelFormat8;
- }
- /// <summary>
- /// 转换图片
- /// </summary>
- /// <param name="nHeight">高</param>
- /// <param name="nWidth">宽</param>
- /// <param name="pImageBuf">图片数据</param>
- /// <param name="enPixelType">像素格式</param>
- public ICogImage ConvertImage(UInt32 nWidth, UInt32 nHeight, IntPtr pImageBuf, GX_PIXEL_FORMAT_ENTRY enPixelType)
- {
- try
- {
- if (enPixelType == GX_PIXEL_FORMAT_ENTRY.GX_PIXEL_FORMAT_MONO8)
- {
- CogImage8Root cogImage8Root = new CogImage8Root();
- cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
- CogImage8Grey cogImage8Grey = new CogImage8Grey();
- cogImage8Grey.SetRoot(cogImage8Root);
- var image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
- System.GC.Collect();
- return image;
- }
- else
- {
- int stride = (int)nWidth * 3;
- CogImage24PlanarColor cogImage24PlanarColor = new CogImage24PlanarColor(new Bitmap((int)nWidth, (int)nHeight, stride, PixelFormat.Format24bppRgb, pImageBuf));
- var m_InputImageRgb24 = cogImage24PlanarColor.Copy(CogImageCopyModeConstants.CopyPixels);
- return m_InputImageRgb24;
- }
- }
- catch (System.Exception)
- {
- return null;
- }
- }
- #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
- }
- }
|