| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127 |
- using Cognex.VisionPro;
- using IKapCDotNet;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Drawing;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using TeamAAS_VP.Core.IKapMethod;
- using TeamAAS_VP.Enums;
- using TeamAAS_VP.Interfaces;
- using TeamAAS_VP.Models;
- namespace TeamAAS_VP.Core.Cameras
- {
- public class IKapCamera : ICamera, INotifyPropertyChanged
- {
- #region 字段
- private IKDevice _ikDevice;
- private Thread _receiveThread;
- private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
- private readonly object _stateLock = new object();
- private readonly object _imageLock = new object();
- private bool _isGrabbing;
- private ICogImage _currentImage;
- private bool _isConnected;
- private string _errorMessage;
- private TimeSpan _totalTime;
- private long _imageWidth;
- private long _imageHeight;
- private uint _imageSize;
- private IntPtr _userBuffer = IntPtr.Zero;
- // 新增:图像格式信息
- private uint _pixelFormat; // 像素格式
- private int _pixelDepth; // 像素深度(位)
- private int _channelDepth; // 通道深度
- private uint _channels; // 通道数
- private bool _isColor; // 是否是彩色图像
- private int _bayerPattern; // Bayer格式(0:非Bayer, 1:BGGR, 2:RGGB, 3:GBRG, 4:GRBG)
- private StringBuilder _pixelFormatString = new StringBuilder(128);
- #endregion
- #region 属性
- public string Name { get; private set; }
- public Guid ID { get; private set; }
- public int Index { get; set; }
- public CameraBrand CameraBrand => CameraBrand.IKap;
- 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; }
- public bool Is3D => false;
- public UInt32 ImageWidth => (UInt32)_imageWidth;
- public UInt32 ImageHeight => (UInt32)_imageHeight;
- public bool IsGrabbing
- {
- get => _isGrabbing;
- private set => SetProperty(ref _isGrabbing, value);
- }
- public ICogImage Image
- {
- get => _currentImage;
- private set => SetProperty(ref _currentImage, value);
- }
- public bool IsConnected
- {
- get => _isConnected;
- private set => SetProperty(ref _isConnected, value);
- }
- public TimeSpan TotalTime
- {
- get => _totalTime;
- private set => SetProperty(ref _totalTime, value);
- }
- public string ErrorMessage
- {
- get => _errorMessage;
- private set => SetProperty(ref _errorMessage, value);
- }
- public int DeviceIndex { get; private set; }
- public int BoardIndex { get; private set; }
- public int DeviceType { get; private set; }
- #endregion
- #region 事件
- public event Action<ICogImage, TimeSpan, string, Guid> ImageCallbackEvent;
- public event Action<Guid, bool> CameraConnectChangedEvent;
- #endregion
- #region 构造函数
- public IKapCamera(Guid id, int index, string name, string serialNumber, string cameraIp, bool isFindByIp)
- {
- ID = id;
- Name = name ?? serialNumber;
- Index = index;
- SerialNumber = serialNumber;
- CameraIp = cameraIp;
- IsFindByIp = isFindByIp;
- _ikDevice = new IKDevice();
- DeviceIndex = -1;
- BoardIndex = -1;
- _isColor = false;
- _pixelDepth = 8;
- _channels = 1;
- }
- public IKapCamera(Guid id, int deviceIndex, int boardIndex, string name, string serialNumber)
- {
- ID = id;
- Name = name;
- Index = deviceIndex;
- SerialNumber = serialNumber;
- DeviceIndex = deviceIndex;
- BoardIndex = boardIndex;
- IsFindByIp = false;
- _ikDevice = new IKDevice();
- _isColor = false;
- _pixelDepth = 8;
- _channels = 1;
- }
- #endregion
- #region 静态方法
- /// <summary>
- /// 获取所有IKap相机设备
- /// </summary>
- public static CameraInfo[] GetDevices()
- {
- List<CameraInfo> cameras = new List<CameraInfo>();
- try
- {
- // 初始化IKap
- uint res = IKapC.ItkManInitialize();
- if (!CheckIKapC(res))
- {
- LogHelper.WriteLogInfo("IKap初始化失败");
- return cameras.ToArray();
- }
- // 获取设备数量
- uint deviceCount = 0;
- res = IKapC.ItkManGetDeviceCount(ref deviceCount);
- if (!CheckIKapC(res) || deviceCount == 0)
- {
- return cameras.ToArray();
- }
- ITKDEV_INFO devInfo = new ITKDEV_INFO();
- ITKGIGEDEV_INFO gvDevInfo = new ITKGIGEDEV_INFO();
- ITK_U3V_DEV_INFO u3vDevInfo = new ITK_U3V_DEV_INFO();
- ITK_CXP_DEV_INFO cxpDevInfo = new ITK_CXP_DEV_INFO();
- ITK_CL_DEV_INFO clDevInfo = new ITK_CL_DEV_INFO();
- ITK_GVB_DEV_INFO gvbDevInfo = new ITK_GVB_DEV_INFO();
- for (uint i = 0; i < deviceCount; i++)
- {
- res = IKapC.ItkManGetDeviceInfo(i, devInfo);
- if (!CheckIKapC(res)) continue;
- CameraInfo cameraInfo = new CameraInfo
- {
- CameraNo = (int)i + 1,
- CameraBrand = CameraBrand.IKap,
- Model = devInfo.ModelName,
- SerialNumber = devInfo.SerialNumber ?? "",
- CameraName = devInfo.FullName,
- ManufacturerName = devInfo.VendorName,
- IsFindByIp = false
- };
- if (devInfo.DeviceClass.CompareTo("GigEVision") == 0)
- {
- res = IKapC.ItkManGetGigEDeviceInfo(i, gvDevInfo);
- if (CheckIKapC(res))
- {
- cameraInfo.CameraType = CameraType.GIGE;
- cameraInfo.CameraIp = gvDevInfo.Ip;
- cameraInfo.IsFindByIp = true;
- }
- }
- else if (devInfo.DeviceClass.CompareTo("USB3Vision") == 0)
- {
- res = IKapC.ItkManGetU3VDeviceInfo(i, u3vDevInfo);
- if (CheckIKapC(res))
- {
- cameraInfo.CameraType = CameraType.USB;
- }
- }
- else if (devInfo.DeviceClass.CompareTo("GigEVisionBoard") == 0)
- {
- res = IKapC.ItkManGetGVBDeviceInfo(i, gvbDevInfo);
- if (CheckIKapC(res))
- {
- cameraInfo.CameraType = CameraType.GIGE;
- cameraInfo.CameraIp = gvbDevInfo.Ip;
- cameraInfo.IsFindByIp = true;
- }
- }
- cameras.Add(cameraInfo);
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("搜索IKap相机列表时出错!", ex);
- }
- return cameras.ToArray();
- }
- /// <summary>
- /// 检查IKap SDK返回状态
- /// </summary>
- private static bool CheckIKapC(uint res)
- {
- if (res != IKapC.ITKSTATUS_OK)
- {
- LogHelper.WriteLogInfo($"IKap错误码: {res:X8}");
- return false;
- }
- return true;
- }
- #endregion
- #region 公共方法
- /// <summary>
- /// 打开相机
- /// </summary>
- public bool OpenDevice()
- {
- _operationSemaphore.Wait();
- try
- {
- if (_ikDevice == null)
- {
- _ikDevice = new IKDevice();
- }
- if (_ikDevice.isOpen())
- {
- IsConnected = true;
- return true;
- }
- // 初始化IKap
- uint res = IKapC.ItkManInitialize();
- if (!CheckIKapC(res))
- {
- LogHelper.WriteLogInfo("IKap初始化失败");
- return false;
- }
- // 查找并打开设备(代码保持不变)
- bool deviceFound = false;
- uint deviceCount = 0;
- res = IKapC.ItkManGetDeviceCount(ref deviceCount);
- if (!CheckIKapC(res))
- {
- ErrorMessage = "获取设备数量失败";
- return false;
- }
- ITKDEV_INFO devInfo = new ITKDEV_INFO();
- for (uint i = 0; i < deviceCount; i++)
- {
- res = IKapC.ItkManGetDeviceInfo(i, devInfo);
- if (!CheckIKapC(res)) continue;
- if (IsFindByIp && !string.IsNullOrEmpty(CameraIp))
- {
- if (devInfo.DeviceClass.CompareTo("GigEVision") == 0)
- {
- ITKGIGEDEV_INFO gvDevInfo = new ITKGIGEDEV_INFO();
- res = IKapC.ItkManGetGigEDeviceInfo(i, gvDevInfo);
- if (CheckIKapC(res))
- {
- string deviceIp = gvDevInfo.Ip;
- if (deviceIp == CameraIp)
- {
- DeviceIndex = (int)i;
- BoardIndex = 0;
- deviceFound = true;
- break;
- }
- }
- }
- }
- else if (!string.IsNullOrEmpty(SerialNumber) && devInfo.SerialNumber == SerialNumber)
- {
- DeviceIndex = (int)i;
- BoardIndex = 0;
- deviceFound = true;
- break;
- }
- else if (DeviceIndex >= 0 && (int)i == DeviceIndex)
- {
- deviceFound = true;
- break;
- }
- }
- if (!deviceFound)
- {
- ErrorMessage = "未找到匹配的相机设备";
- return false;
- }
- bool opened = _ikDevice.openDevice(DeviceIndex, BoardIndex);
- if (!opened)
- {
- ErrorMessage = "打开设备失败";
- return false;
- }
- /* 获取采集卡图像宽度 */
- int width = 0;
- var ret = IKapBoardDotNet.IKapBoard.IKapGetInfo(_ikDevice.m_pBoard, (uint)IKapBoardDotNet.IKapBoard.IKP_IMAGE_WIDTH, ref width);
- /* 获取采集卡图像高度 */
- int height = 0;
- ret = IKapBoardDotNet.IKapBoard.IKapGetInfo(_ikDevice.m_pBoard, (uint)IKapBoardDotNet.IKapBoard.IKP_IMAGE_HEIGHT, ref height);
- // 获取图像尺寸和格式信息
- _imageWidth = _ikDevice.m_nWidth = width;
- _imageHeight = _ikDevice.m_nHeight = height;
- // 获取图像格式信息
- GetImageFormatInfo();
- ManufacturerName = _ikDevice.m_devName ?? "";
- ModelName = _ikDevice.m_devName ?? "";
- IsConnected = true;
- CameraConnectChangedEvent?.Invoke(ID, true);
- ErrorMessage = "";
- return true;
- }
- catch (Exception ex)
- {
- ErrorMessage = ex.Message;
- LogHelper.WriteLogError("打开IKap相机失败", ex);
- return false;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 异步打开相机
- /// </summary>
- public Task<bool> OpenDeviceAsync()
- {
- return Task.Run(() => OpenDevice());
- }
- /// <summary>
- /// 关闭相机
- /// </summary>
- public void CloseDevice()
- {
- _operationSemaphore.Wait();
- try
- {
- StopGrabbing();
- if (_ikDevice != null && _ikDevice.isOpen())
- {
- _ikDevice.closeDevice();
- }
- // 释放用户缓冲区
- if (_userBuffer != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(_userBuffer);
- _userBuffer = IntPtr.Zero;
- }
- IsConnected = false;
- CameraConnectChangedEvent?.Invoke(ID, false);
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- // 注意:需要更新 Grab 方法中的图像获取部分
- public ICogImage Grab(bool isRealtime = true)
- {
- // _operationSemaphore.Wait();
- try
- {
- Stopwatch sw = Stopwatch.StartNew();
- if (!IsConnected)
- {
- if (!OpenDevice())
- {
- return null;
- }
- }
- _ikDevice.releaseStream();
- // 创建流
- if (!_ikDevice.createStream())
- {
- ErrorMessage = "创建流失败";
- return null;
- }
- //开始采集前执行关闭操作,防止相机已经处于采集状态
- if (!_ikDevice.stopGrab())
- return null;
- // 开始采集单帧
- if (!_ikDevice.startGrab(1))
- {
- ErrorMessage = "开始采集失败";
- return null;
- }
- // 等待采集完成
- _ikDevice.waitGrab();
- if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
- {
- // 使用新的图像转换方法
- Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
- _ikDevice.m_bUpdateImage = false;
- }
- // 获取图像数据
- //lock (_imageLock)
- //{
- // if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
- // {
- // // 使用新的图像转换方法
- // Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
- // _ikDevice.m_bUpdateImage = false;
- // }
- //}
- // 停止采集
- _ikDevice.stopGrab();
- _ikDevice.releaseStream();
- TotalTime = sw.Elapsed;
- if (Image == null)
- {
- ErrorMessage = "采集图像为空";
- }
- else
- {
- ErrorMessage = "";
- }
- return Image;
- }
- catch (Exception ex)
- {
- ErrorMessage = ex.Message;
- LogHelper.WriteLogError("采集图像失败", ex);
- return null;
- }
- finally
- {
- // _operationSemaphore.Release();
- }
- }
- // 注意:需要更新 Grab 方法中的图像获取部分
- public ICogImage Grab2(bool isRealtime = true)
- {
- _operationSemaphore.Wait();
- try
- {
- Stopwatch sw = Stopwatch.StartNew();
- if (!IsConnected)
- {
- if (!OpenDevice())
- {
- return null;
- }
- }
- _ikDevice.releaseStream();
- // 创建流
- if (!_ikDevice.createStream())
- {
- ErrorMessage = "创建流失败";
- return null;
- }
- //开始采集前执行关闭操作,防止相机已经处于采集状态
- if (!_ikDevice.stopGrab())
- return null;
- // 开始采集单帧
- if (!_ikDevice.startGrab(1))
- {
- ErrorMessage = "开始采集失败";
- return null;
- }
- // 等待采集完成
- _ikDevice.waitGrab();
- // 获取图像数据
- lock (_imageLock)
- {
- if (_ikDevice.m_pUserBuffer != IntPtr.Zero && _ikDevice.m_bUpdateImage)
- {
- // 使用新的图像转换方法
- Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
- _ikDevice.m_bUpdateImage = false;
- }
- }
- // 停止采集
- _ikDevice.stopGrab();
- _ikDevice.releaseStream();
- TotalTime = sw.Elapsed;
- if (Image == null)
- {
- ErrorMessage = "采集图像为空";
- }
- else
- {
- ErrorMessage = "";
- }
- return Image;
- }
- catch (Exception ex)
- {
- ErrorMessage = ex.Message;
- LogHelper.WriteLogError("采集图像失败", ex);
- return null;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 开始实时采集
- /// </summary>
- public void StartGrabbing()
- {
- lock (_stateLock)
- {
- if (_isGrabbing) return;
- _isGrabbing = true;
- }
- if (!IsConnected)
- {
- OpenDevice();
- }
- _receiveThread = new Thread(GrabbingThreadProc) { IsBackground = true };
- _receiveThread.Start();
- }
- /// <summary>
- /// 停止实时采集
- /// </summary>
- public void StopGrabbing()
- {
- lock (_stateLock)
- {
- _isGrabbing = false;
- }
- Thread.Sleep(100);
- if (_receiveThread != null && _receiveThread.IsAlive)
- {
- try
- {
- _receiveThread.Join(1000);
- }
- catch { }
- _receiveThread = null;
- }
- if (_ikDevice != null && _ikDevice.m_bGrabingImage)
- {
- _ikDevice.stopGrab();
- _ikDevice.releaseStream();
- }
- }
- /// <summary>
- /// 设置曝光时间
- /// </summary>
- public bool SetExposureTime(float exposureTime)
- {
- _operationSemaphore.Wait();
- try
- {
- if (!IsConnected || _ikDevice.m_hDev.unused == 0)
- {
- return false;
- }
- uint res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "ExposureTime", exposureTime);
- return CheckIKapC(res);
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 获取曝光时间
- /// </summary>
- public float GetExposureTime()
- {
- _operationSemaphore.Wait();
- try
- {
- if (!IsConnected || _ikDevice.m_hDev.unused == 0)
- {
- return 0;
- }
- double value = 0;
- uint res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "ExposureTime", ref value);
- return CheckIKapC(res) ? (float)value : 0;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 设置增益
- /// </summary>
- public bool SetGain(float gain)
- {
- //_operationSemaphore.Wait();
- //try
- //{
- // if (!IsConnected || _ikDevice.m_hDev.unused == 0)
- // {
- // return false;
- // }
- // 尝试使用AnalogGain
- // uint res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "AnalogGain", gain);
- // if (!CheckIKapC(res))
- // {
- // 如果AnalogGain不支持,尝试Gain
- // res = IKapC.ItkDevSetDouble(_ikDevice.m_hDev, "Gain", gain);
- // return CheckIKapC(res);
- // }
- // return true;
- //}
- //finally
- //{
- // _operationSemaphore.Release();
- //}
- return true;
- }
- /// <summary>
- /// 获取增益
- /// </summary>
- public float GetGain()
- {
- _operationSemaphore.Wait();
- try
- {
- if (!IsConnected || _ikDevice.m_hDev.unused == 0)
- {
- return 0;
- }
- double value = 0;
- uint res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "AnalogGain", ref value);
- if (!CheckIKapC(res))
- {
- res = IKapC.ItkDevGetDouble(_ikDevice.m_hDev, "Gain", ref value);
- if (!CheckIKapC(res))
- {
- return 0;
- }
- }
- return (float)value;
- }
- finally
- {
- _operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 检查相机软件是否安装
- /// </summary>
- /// <returns></returns>
- public static (bool isInstalled, string version) CheckSoftwareInstalled()
- {
- return (true, "");
- }
- #endregion
- #region 私有方法
- // 更新实时采集线程
- private void GrabbingThreadProc()
- {
- try
- {
- if (!_ikDevice.createStream())
- {
- ErrorMessage = "创建流失败";
- return;
- }
- if (!_ikDevice.startGrab(0))
- {
- ErrorMessage = "开始连续采集失败";
- return;
- }
- while (_isGrabbing)
- {
- Stopwatch sw = Stopwatch.StartNew();
- int waitCount = 0;
- while (_isGrabbing && !_ikDevice.m_bUpdateImage && waitCount < 50)
- {
- Thread.Sleep(10);
- waitCount++;
- }
- if (_ikDevice.m_bUpdateImage)
- {
- lock (_imageLock)
- {
- if (_ikDevice.m_pUserBuffer != IntPtr.Zero)
- {
- // 使用新的图像转换方法
- Image = ConvertBufferToCogImage(_ikDevice.m_pUserBuffer);
- _ikDevice.m_bUpdateImage = false;
- }
- }
- TotalTime = sw.Elapsed;
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage, ID);
- }
- Thread.Sleep(1);
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("实时采集线程异常", ex);
- ErrorMessage = ex.Message;
- }
- finally
- {
- _ikDevice.stopGrab();
- _ikDevice.releaseStream();
- IsGrabbing = false;
- }
- }
- #endregion
- #region 私有方法 - 图像转换
- /// <summary>
- /// 获取图像像素格式信息
- /// </summary>
- private bool GetImageFormatInfo()
- {
- try
- {
- if (_ikDevice.m_hDev.unused == 0)
- return false;
- uint res = IKapC.ITKSTATUS_OK;
- // 获取像素格式字符串
- uint pixelFormatSize = 128;
- res = IKapC.ItkDevToString(_ikDevice.m_hDev, "PixelFormat", _pixelFormatString, ref pixelFormatSize);
- if (!CheckIKapC(res))
- {
- LogHelper.WriteLogInfo("获取PixelFormat失败");
- return false;
- }
- // 获取像素格式值
- res = IKapC.ItkDevGetPixelFormatVal(_ikDevice.m_hDev, _pixelFormatString.ToString(), ref _pixelFormat);
- if (!CheckIKapC(res))
- {
- LogHelper.WriteLogInfo("获取PixelFormat值失败");
- return false;
- }
- // 获取通道深度(每个通道的位数)
- _channelDepth = (int)IKapC.ITKBUFFER_FORMAT_CHANNEL_BITS(_pixelFormat);
- // 获取像素深度(每个像素的总位数)
- _pixelDepth = (int)IKapC.ITKBUFFER_FORMAT_PIXEL_BITS(_pixelFormat);
- // 获取通道数
- _channels = (uint)(_pixelDepth / _channelDepth);
- // 判断是否为彩色图像
- string pixelFormatStr = _pixelFormatString.ToString().ToUpper();
- _isColor = pixelFormatStr.Contains("RGB") ||
- pixelFormatStr.Contains("BGR") ||
- pixelFormatStr.Contains("YUV") ||
- (_channels >= 3);
- // 检查是否为Bayer格式
- if (pixelFormatStr.Contains("BAYER"))
- {
- if (pixelFormatStr.Contains("BGGR"))
- _bayerPattern = 1;
- else if (pixelFormatStr.Contains("RGGB"))
- _bayerPattern = 2;
- else if (pixelFormatStr.Contains("GBRG"))
- _bayerPattern = 3;
- else if (pixelFormatStr.Contains("GRBG"))
- _bayerPattern = 4;
- _isColor = true; // Bayer格式最终会转换为彩色
- }
- LogHelper.WriteLogInfo($"图像格式: {_pixelFormatString}, 像素深度={_pixelDepth}, 通道数={_channels}, 彩色={_isColor}");
- return true;
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("获取图像格式信息失败", ex);
- return false;
- }
- }
- /// <summary>
- /// 将原始缓冲区数据转换为ICogImage
- /// </summary>
- private ICogImage ConvertBufferToCogImage(IntPtr buffer)
- {
- if (buffer == IntPtr.Zero || _imageWidth <= 0 || _imageHeight <= 0)
- {
- return null;
- }
- try
- {
- int width = (int)_imageWidth;
- int height = (int)_imageHeight;
- ICogImage tempImage = null;
- // 处理Bayer格式
- IntPtr convertedBuffer = buffer;
- bool needFree = false;
- if (_bayerPattern != 0 && _pixelDepth == 8)
- {
- int rgbSize = width * height * 3;
- IntPtr rgbBuffer = Marshal.AllocHGlobal(rgbSize);
- if (IKDevice.Bayer2RGB(buffer, _pixelFormat, ref rgbBuffer,
- IKapC.ITKBUFFER_VAL_FORMAT_BGR888, width, height, _bayerPattern))
- {
- convertedBuffer = rgbBuffer;
- needFree = true;
- _isColor = true;
- _pixelDepth = 24;
- }
- else
- {
- Marshal.FreeHGlobal(rgbBuffer);
- return null;
- }
- }
- // 创建临时图像(可能只是引用数据)
- if (_isColor || _channels >= 3)
- {
- if (_pixelDepth == 24 || _pixelDepth == 8 * 3)
- {
- tempImage = CreateColorImage(convertedBuffer, width, height);
- }
- }
- else
- {
- if (_pixelDepth == 8)
- {
- tempImage = CreateGreyImage(convertedBuffer, width, height);
- }
- else if (_pixelDepth == 16)
- {
- tempImage = CreateGreyImage16(convertedBuffer, width, height);
- }
- }
- if (tempImage == null)
- {
- return null;
- }
- // ✅ 关键:强制创建独立副本
- ICogImage result = null;
- // 方法1:使用 CopyBase 创建可独立管理的副本
- if (tempImage is CogImage8Grey grey8Image)
- {
- result = grey8Image.CopyBase(CogImageCopyModeConstants.CopyPixels);
- }
- else if (tempImage is CogImage16Grey grey16Image)
- {
- result = grey16Image.CopyBase(CogImageCopyModeConstants.CopyPixels);
- }
- else if (tempImage is CogImage24PlanarColor colorImage)
- {
- result = colorImage.CopyBase(CogImageCopyModeConstants.CopyPixels);
- }
- else
- {
- // 方法2:转换为 Bitmap 再转回(最稳妥)
- using (Bitmap bitmap = tempImage.ToBitmap())
- {
- if (_isColor)
- {
- result = new CogImage24PlanarColor(bitmap);
- }
- else
- {
- result = new CogImage8Grey(bitmap);
- }
- }
- }
- // 释放临时图像(如果它是独立的对象)
- //if (tempImage != null && tempImage != result)
- //{
- // Marshal.ReleaseComObject(tempImage);
- //}
- //// ✅ 只有在确保图像数据已经被复制后,才能释放临时缓冲区
- //if (needFree && convertedBuffer != IntPtr.Zero)
- //{
- // Marshal.FreeHGlobal(convertedBuffer);
- //}
- return result;
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("转换图像数据失败", ex);
- return null;
- }
- }
- /// <summary>
- /// 创建8位灰度图像
- /// </summary>
- private ICogImage CreateGreyImage(IntPtr buffer, int width, int height)
- {
- try
- {
- CogImage8Root greyRoot = new CogImage8Root();
- greyRoot.Initialize(width, height, buffer, width, null);
- CogImage8Grey greyImage = new CogImage8Grey();
- greyImage.SetRoot(greyRoot);
- return greyImage;
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("创建8位灰度图像失败", ex);
- return null;
- }
- }
- /// <summary>
- /// 创建16位灰度图像
- /// </summary>
- private ICogImage CreateGreyImage16(IntPtr buffer, int width, int height)
- {
- try
- {
- // 使用CogImage16Grey(如果VisionPro支持)
- // 如果不支持,可以转换为8位
- CogImage16Root grey16Root = new CogImage16Root();
- grey16Root.Initialize(width, height, buffer, width * 2, null);
- CogImage16Grey grey16Image = new CogImage16Grey();
- grey16Image.SetRoot(grey16Root);
- return grey16Image;
- }
- catch
- {
- // 如果不支持16位,转换为8位
- int size = width * height;
- byte[] grey8Data = new byte[size];
- unsafe
- {
- ushort* src = (ushort*)buffer.ToPointer();
- for (int i = 0; i < size; i++)
- {
- grey8Data[i] = (byte)(src[i] >> 8);
- }
- }
- IntPtr grey8Buffer = Marshal.AllocHGlobal(size);
- Marshal.Copy(grey8Data, 0, grey8Buffer, size);
- CogImage8Root grey8Root = new CogImage8Root();
- grey8Root.Initialize(width, height, grey8Buffer, width, null);
- CogImage8Grey grey8Image = new CogImage8Grey();
- grey8Image.SetRoot(grey8Root);
- Marshal.FreeHGlobal(grey8Buffer);
- return grey8Image;
- }
- }
- /// <summary>
- /// 创建24位彩色图像(RGB/BGR)
- /// </summary>
- private ICogImage CreateColorImage(IntPtr buffer, int width, int height)
- {
- try
- {
- unsafe
- {
- byte* pixelData = (byte*)buffer.ToPointer();
- byte[] redPlane = new byte[width * height];
- byte[] greenPlane = new byte[width * height];
- byte[] bluePlane = new byte[width * height];
- // 假设是BGR格式(大多数相机使用BGR)
- for (int i = 0; i < width * height; i++)
- {
- bluePlane[i] = pixelData[3 * i];
- greenPlane[i] = pixelData[3 * i + 1];
- redPlane[i] = pixelData[3 * i + 2];
- }
- // 分配非托管内存
- IntPtr redPtr = Marshal.AllocHGlobal(redPlane.Length);
- IntPtr greenPtr = Marshal.AllocHGlobal(greenPlane.Length);
- IntPtr bluePtr = Marshal.AllocHGlobal(bluePlane.Length);
- Marshal.Copy(redPlane, 0, redPtr, redPlane.Length);
- Marshal.Copy(greenPlane, 0, greenPtr, greenPlane.Length);
- Marshal.Copy(bluePlane, 0, bluePtr, bluePlane.Length);
- CogImage8Root redRoot = new CogImage8Root();
- CogImage8Root greenRoot = new CogImage8Root();
- CogImage8Root blueRoot = new CogImage8Root();
- redRoot.Initialize(width, height, redPtr, width, null);
- greenRoot.Initialize(width, height, greenPtr, width, null);
- blueRoot.Initialize(width, height, bluePtr, width, null);
- CogImage24PlanarColor image = new CogImage24PlanarColor();
- image.SetRoots(redRoot, greenRoot, blueRoot);
- // 注意:这里分配的内存需要在图像使用完毕后释放
- // 但由于CogImage可能持有引用,需要妥善处理
- // 简单起见,先不释放,在实际使用中需要管理生命周期
- return image;
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("创建彩色图像失败", ex);
- return null;
- }
- }
- #endregion
- #region INotifyPropertyChanged
- public event PropertyChangedEventHandler PropertyChanged;
- 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;
- }
- protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- #endregion
- }
- }
|