| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079 |
- 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;
- 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("未安装Galaxy Viewer");
- return cameras.ToArray();
- }
- m_listIGXDeviceInfo.Clear();
- if (null != m_objIGXFactory)
- {
- m_objIGXFactory.UpdateAllDeviceList(200, m_listIGXDeviceInfo);
- }
- // 判断当前连接设备个数
- if (m_listIGXDeviceInfo.Count <= 0)
- {
- LogHelper.WriteLogInfo("未检测到设备,请确保设备正常连接然后重启程序!");
- 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();
- }
- }
- /// <summary>
- /// 采集单张图片
- /// </summary>
- /// <param name="lastImageOnly">true:采集一张新图像,false:返回最后一张图像</param>
- /// <returns></returns>
- public ICogImage Grab(bool lastImageOnly = true)
- {
- 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
- }
- }
|