| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120 |
- 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();
- // 获取图像数据
- 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
- }
- }
|