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 ImageCallbackEvent; public event Action 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 静态方法 /// /// 获取所有IKap相机设备 /// public static CameraInfo[] GetDevices() { List cameras = new List(); 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(); } /// /// 检查IKap SDK返回状态 /// private static bool CheckIKapC(uint res) { if (res != IKapC.ITKSTATUS_OK) { LogHelper.WriteLogInfo($"IKap错误码: {res:X8}"); return false; } return true; } #endregion #region 公共方法 /// /// 打开相机 /// 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(); } } /// /// 异步打开相机 /// public Task OpenDeviceAsync() { return Task.Run(() => OpenDevice()); } /// /// 关闭相机 /// 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(); // 获取图像数据 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(); } } /// /// 开始实时采集 /// public void StartGrabbing() { lock (_stateLock) { if (_isGrabbing) return; _isGrabbing = true; } if (!IsConnected) { OpenDevice(); } _receiveThread = new Thread(GrabbingThreadProc) { IsBackground = true }; _receiveThread.Start(); } /// /// 停止实时采集 /// 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(); } } /// /// 设置曝光时间 /// 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(); } } /// /// 获取曝光时间 /// 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(); } } /// /// 设置增益 /// 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; } /// /// 获取增益 /// 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(); } } /// /// 检查相机软件是否安装 /// /// 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 私有方法 - 图像转换 /// /// 获取图像像素格式信息 /// 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; } } /// /// 将原始缓冲区数据转换为ICogImage /// 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; } } /// /// 创建8位灰度图像 /// 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; } } /// /// 创建16位灰度图像 /// 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; } } /// /// 创建24位彩色图像(RGB/BGR) /// 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(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer.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 } }