C3032
2026-01-08 7279c77f318cd7e38af279dc98a1fecec33f5e30
优化相机采集逻辑与亮度图处理功能

- 修改 `VisionForm.cs` 中相机初始化时的句柄参数。
- 更新 `2DCameraForm.cs` 中的相机初始化逻辑,增加品牌显示控制。
- 增加对 LBCamera 的特殊处理,确保 SDK 自动显示模式下不需手动更新图像。
- 在 `BaseCamera.cs` 中新增单次采集模式的抽象方法并重构现有采集方法。
- 重写 `HRCamera.cs` 中的 `StartContinuousGrab` 方法以返回 `true`。
- 在 `ICamera.cs` 中新增连续采集模式的接口定义。
- 重构 `LBCamera.cs` 中的初始化、关闭、采集等方法,支持 SDK 自动显示模式并优化图像处理逻辑。
- 新增图像参数更新逻辑,确保相机参数同步。
- 重构图像获取逻辑,确保在 SDK 自动显示模式下正确处理图像采集。
已修改8个文件
645 ■■■■■ 文件已修改
LB_SmartVision/Forms/Pages/CameraPage/CameraForm.cs 4 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_SmartVision/VisionForm.cs 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_SmartVisionCameraSDK/PHM6000/PHM6000Profiler.cs 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_VisionProcesses/Cameras/2DCameraForm.cs 207 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_VisionProcesses/Cameras/BaseCamera.cs 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_VisionProcesses/Cameras/ICamera.cs 9 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs 370 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
LB_SmartVision/Forms/Pages/CameraPage/CameraForm.cs
@@ -85,7 +85,9 @@
            else
                camera.SetTriggerMode(TriggerMode.On, TriggerSource.Line0);
            camera.StartGrabbing();
            // 注释掉自动启动采集逻辑,防止关闭窗体后相机自动连续采集
            // 用户需要手动点击"启动采集"按钮才会启动相机
            // camera.StartGrabbing();
            Unsubscribe();
        }
LB_SmartVision/VisionForm.cs
@@ -699,7 +699,7 @@
                        }
                }
                camera.SN = CameraConnectionString.Key;
                if (!camera.InitDevice(CameraConnectionString.Key, this.Handle))
                if (!camera.InitDevice(CameraConnectionString.Key, IntPtr.Zero))
                {
                    LogInfo($"初始化相机[{CameraConnectionString.Key}]失败", LogInfoType.ERROR);
                    if (camera != null)
LB_SmartVisionCameraSDK/PHM6000/PHM6000Profiler.cs
@@ -874,6 +874,35 @@
        /// <param name="KeepImageSize">图像大小是否保持</param>
        [DllImport("PHM6000API", CallingConvention = CallingConvention.StdCall, EntryPoint = "SetTransformParameter")]
        public static extern void SetTransformParameter(IntPtr pHandle, float fAngle, int xOffset, int yOffset, int hMirror, int vMirror, int KeepImageSize = 0);
        #region PointCloud3D Functions
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "AddZAPoints")]
        public static extern int AddZAPoints(IntPtr pInstance, IntPtr points, int nCount, float fStepX, float fStepY, int nDownSample);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "ClearPCLPoints")]
        public static extern int ClearPCLPoints(IntPtr pInstance);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetPointCloudBound")]
        public static extern int GetPointCloudBound(IntPtr pInstance, ref double pMin, ref double pMax);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "RenderPCLWindow")]
        public static extern void RenderPCLWindow(IntPtr pInstance, int nWidth, int nHeight);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "SetLookUpTableRange")]
        public static extern void SetLookUpTableRange(IntPtr pInstance, double fMin, double fMax);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "ShowCubeAxes")]
        public static extern void ShowCubeAxes(IntPtr pInstance, int bInit);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "ShowLookUpTable")]
        public static extern void ShowLookUpTable(IntPtr pInstance, double x, double y, double xWide, double yWide);
        [DllImport("PointCloud3D", CallingConvention = CallingConvention.StdCall, EntryPoint = "UpdatePCLPointColors")]
        public static extern int UpdatePCLPointColors(IntPtr pInstance, string szColoring);
        #endregion
        /// <summary>
        /// 将结构体指针转换为double(模拟C++的(double)(int64)&操作)
        /// </summary>
LB_VisionProcesses/Cameras/2DCameraForm.cs
@@ -252,7 +252,18 @@
                        return;
                }
                if (cmbSN.Items.Count > 0 && camera.InitDevice(cmbSN.Text.ToString(), this.Handle))
                IntPtr displayHandle = onlinePictureBox.Handle;
                if (brand == CameraBrand.LBCamera)
                {
                    onlinePictureBox.Visible = false;
                    displayHandle = this.panel_Picture.Handle;
                }
                else
                {
                    onlinePictureBox.Visible = true;
                }
                if (cmbSN.Items.Count > 0 && camera.InitDevice(cmbSN.Text.ToString(), displayHandle))
                {
                    camera.ImageGrabbed -= GetImageBllComplete;
                    camera.ImageGrabbed += GetImageBllComplete;
@@ -295,8 +306,10 @@
            if (camera.CloseDevice())
            {
                onlinePictureBox.Visible = true;
                MessageBox.Show(camera.SN + "断开成功");
                this.panel_Picture.Controls.Clear();
                this.panel_Picture.Controls.Add(onlinePictureBox);
            }
        }
@@ -382,28 +395,42 @@
        /// <summary>
        /// 相机回调运行
        /// 注意:对于LBCamera(3D线扫相机),使用SDK自动显示模式
        /// SDK会自动将图像显示到对应的控件上,此回调只用于统计采集次数
        /// </summary>
        /// <param name="CCDName"></param>
        /// <param name="image"></param>
        private void GetImageBllComplete(object sender, CameraEventArgs e)
        {
            // 对于LBCamera(SDK自动显示模式),Bitmap为null,我们只需要统计
            if (camera.Brand == CameraBrand.LBCamera)
            {
                if (e is LBCameraEventArgs args && args.IsComplete)
                {
                    total.iImageCount++;
                    // 不需要更新onlinePictureBox.Image,SDK会自动显示
                }
                return;
            }
            // 对于2D相机(手动处理模式)
            if (e.Bitmap == null)
                return;
                lock (e.Bitmap)
            lock (e.Bitmap)
            {
                if (this.InvokeRequired) // 检查是否需要在UI线程上调用
                {
                    if (this.InvokeRequired) // 检查是否需要在UI线程上调用
                    {
                        this.Invoke(new Action(() =>
                        {
                            onlinePictureBox.Image = e.Bitmap;
                        })); // 递归调用自身,但这次在UI线程上
                    }
                    else
                    this.Invoke(new Action(() =>
                    {
                        onlinePictureBox.Image = e.Bitmap;
                    }
                    })); // 递归调用自身,但这次在UI线程上
                }
                else
                {
                    onlinePictureBox.Image = e.Bitmap;
                }
            }
            total.iImageCount++;
            try
            {
@@ -426,23 +453,121 @@
            Task.Factory.StartNew(() =>
            {
                //camera.GetCamConfig(out CameraConfig OriCamConfig);
                // 设置曝光和增益
                camera.SetExpouseTime(Convert.ToDouble(txtExp.Text));
                camera.SetGain(Convert.ToDouble(txtGain.Text));
                camera.GetImageWithSoftTrigger(out Bitmap bitmap);
                bool success = false;
                Bitmap bitmap = null;
                this.BeginInvoke(new Action(() =>
                // 调用基类接口的单次采集方法
                // LBCamera重写了StartSingleGrab方法,其他相机调用返回false
                success = camera.StartSingleGrab();
                if (success)
                {
                    if (bitmap != null)
                        this.lblCapTime.Text = $"{(DateTime.Now - StartTime).TotalMilliseconds}ms";
                    else
                        this.lblCapTime.Text = "-1ms";
                }));
                    // 对于LBCamera(SDK自动显示模式),等待采集完成即可
                    // 对于2D相机,等待Bitmap事件
                    if (camera.Brand == CameraBrand.LBCamera)
                    {
                        // SDK自动显示模式下,等待采集完成
                        using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                        {
                            bool captured = false;
                            EventHandler<CameraEventArgs> handler = (s, evt) =>
                            {
                                if (evt is LBCameraEventArgs args && args.IsComplete)
                                {
                                    captured = true;
                                    waitHandle.Set();
                                }
                            };
                //复原原通讯口设置
                //camera.SetCamConfig(OriCamConfig);
                            camera.ImageGrabbed += handler;
                            try
                            {
                                // 等待5秒超时
                                if (waitHandle.WaitOne(5000))
                                {
                                    // SDK自动显示模式,不返回Bitmap
                                    // 但采集已完成
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    this.lblCapTime.Text = $"{(DateTime.Now - StartTime).TotalMilliseconds}ms";
                                }));
                            }
                            finally
                            {
                                camera.ImageGrabbed -= handler;
                                camera.StopGrabbing();
                            }
                        }
                    }
                    else
                    {
                        // 对于2D相机,等待图像数据
                        using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                        {
                            Bitmap captured = null;
                            EventHandler<CameraEventArgs> handler = (s, evt) =>
                            {
                                // 对于2D相机,直接接收图像
                                if (!(evt is LBCameraEventArgs) && evt.Bitmap != null)
                                {
                                    captured = evt.Bitmap.Clone() as Bitmap;
                                    waitHandle.Set();
                                }
                            };
                            camera.ImageGrabbed += handler;
                            try
                            {
                                // 等待5秒超时
                                if (waitHandle.WaitOne(5000))
                                {
                                    bitmap = captured;
                                }
                            }
                            finally
                            {
                                camera.ImageGrabbed -= handler;
                                camera.StopGrabbing();
                            }
                        }
                        this.BeginInvoke(new Action(() =>
                        {
                            if (bitmap != null)
                            {
                                this.lblCapTime.Text = $"{(DateTime.Now - StartTime).TotalMilliseconds}ms";
                                onlinePictureBox.Image = bitmap;
                            }
                            else
                            {
                                this.lblCapTime.Text = "-1ms";
                            }
                        }));
                    }
                }
                else
                {
                    // 如果StartSingleGrab失败,回退到传统的GetImageWithSoftTrigger
                    camera.GetImageWithSoftTrigger(out bitmap);
                    this.BeginInvoke(new Action(() =>
                    {
                        if (bitmap != null)
                        {
                            this.lblCapTime.Text = $"{(DateTime.Now - StartTime).TotalMilliseconds}ms";
                            onlinePictureBox.Image = bitmap;
                        }
                        else
                        {
                            this.lblCapTime.Text = "-1ms";
                        }
                    }));
                }
            });
        }
@@ -453,12 +578,12 @@
            total.Clear();
            // 尝试将输入字符串转换为枚举值
            if (Enum.TryParse(cmbBrand.Text, true, out CameraBrand brand))
            {
                camera.StopGrabbing();
                camera.StartWith_HardTriggerModel();
            }
            // 停止当前采集
            camera.StopGrabbing();
            // 调用基类接口的连续采集方法
            // LBCamera会调用StartContinuousGrab方法,其他相机使用原有的StartWith_HardTriggerModel
            camera.StartContinuousGrab();
            startGrabtime = DateTime.Now;
@@ -473,18 +598,15 @@
            total.Clear();
            // 尝试将输入字符串转换为枚举值
            if (Enum.TryParse(cmbBrand.Text, true, out CameraBrand brand))
            {
                Task.Factory.StartNew(() =>
                {
                    camera.StopGrabbing();
                    camera.StartWith_SoftTriggerModel();
            // 停止当前采集
            camera.StopGrabbing();
                });
            }
            // 调用基类接口的连续采集方法
            // LBCamera会调用StartContinuousGrab方法,其他相机使用原有的StartWith_SoftTriggerModel
            camera.StartContinuousGrab();
            startGrabtime = DateTime.Now;
            cmbSN.Enabled = false;
            cmbBrand.Enabled = false;
        }
@@ -655,6 +777,10 @@
        private void CameraForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            onlinePictureBox.Visible = true;
            this.panel_Picture.Controls.Clear();
            this.panel_Picture.Controls.Add(onlinePictureBox);
            this.onlinePictureBox.Image = null;
            if (camera != null)
            {
@@ -667,7 +793,12 @@
                else
                    camera.SetTriggerMode(TriggerMode.On, actualSource);
                camera.StartGrabbing();
                // LBCamera在StartGrabbing时会直接开启激光和采集,因此关闭窗口时不应自动重启采集
                // 其他相机(如2D相机)通常需要保持Grabbing状态以接收触发
                if (camera.Brand != CameraBrand.LBCamera)
                {
                    camera.StartGrabbing();
                }
            }
            //路径为空说明为测试模式,需要释放相机
LB_VisionProcesses/Cameras/BaseCamera.cs
@@ -186,12 +186,29 @@
        #region  protected abstract
        /// <summary>
        /// 开始采图
        /// 开始采图(默认连续采集)
        /// </summary>
        /// <returns></returns>
        public abstract bool StartGrabbing();
        /// <summary>
        /// 单次采集模式(适用于线扫相机)
        /// </summary>
        /// <returns></returns>
        public virtual bool StartSingleGrab()
        {
            // 默认实现:普通相机不支持单次采集,直接返回false
            // 线扫相机需要重写此方法
            return false;
        }
        /// <summary>
        /// 连续采集模式
        /// </summary>
        /// <returns></returns>
        public abstract bool StartContinuousGrab();
        /// <summary>
        /// 停止采图
        /// </summary>
        /// <returns></returns>
LB_VisionProcesses/Cameras/HRCameras/HRCamera.cs
@@ -1247,6 +1247,11 @@
            config.Params.Inputs.Add("增益", gain);
        }
        public override bool StartContinuousGrab()
        {
            return true;
        }
        #endregion
    }
}
LB_VisionProcesses/Cameras/ICamera.cs
@@ -79,11 +79,18 @@
        bool GetImageWithSoftTrigger(out Bitmap bitmap, int outtime = 3000);
        /// <summary>
        /// 软触发
        /// 软触发单次
        /// </summary>
        /// <returns></returns>
        bool SoftTrigger();
        /// <summary>
        /// 连续采集模式
        /// </summary>
        /// <returns></returns>
        bool StartContinuousGrab();
        #endregion
        #region SettingConfig
LB_VisionProcesses/Cameras/LBCameras/LBCamera.cs
@@ -13,6 +13,15 @@
namespace LB_VisionProcesses.Cameras.LBCameras
{
    public class LBCameraEventArgs : CameraEventArgs
    {
        public bool IsComplete { get; set; }
        public LBCameraEventArgs(string sn, Bitmap bitmap, bool isComplete) : base(sn, bitmap)
        {
            IsComplete = isComplete;
        }
    }
    /// <summary>
    /// LB3D工业相机实现类
    /// 基于PHM6000系列封装
@@ -21,14 +30,22 @@
    {
        private IntPtr _cameraHandle = IntPtr.Zero;
        private PHM6000SensorConfig _sensorConfig;
        private AcquisitionCallbackZA _acquisitionCallback;
        private AcquisitionCompletedCallback _acquisitionCompletedCallback;
        private bool _isConnected = false;
        private int _frameCount = 0; // 采集帧计数
        // 图像缓冲
        private List<byte[]> _lineDataBuffer = new List<byte[]>();
        private readonly object _bufferLock = new object();
        private int _currentLineCount = 0;
        // 实时显示用的Bitmap
        private Bitmap _currentBitmap = null;
        private byte[] _rawPixelBuffer = null; // 用于存储像素数据,避免频繁LockBits
        private int _currentBitmapHeight = 0;
        private int _currentBitmapWidth = 0;
        private object _bitmapLock = new object();
        private DateTime _lastUpdateTime = DateTime.MinValue;
        // 显示句柄和函数(与LLSystem示例保持一致)
        private IntPtr _lightPic = IntPtr.Zero;
@@ -36,16 +53,71 @@
        private IntPtr _pointPic = IntPtr.Zero;
        private IntPtr _outlinePic = IntPtr.Zero;
        // 显示控制函数结构体
        private PILOT2D_FUNC _func2d;
        private VTK3D_FUNC _func3d;
        public LBCamera()
        {
            Brand = CameraBrand.LBCamera;
            _sensorConfig = new PHM6000SensorConfig();
            // 初始化2D显示函数
            _func2d = new PILOT2D_FUNC
            {
                AddBarycentreDataZA = Pilot2D.AddBarycentreDataZA,
                AddDepthData = Pilot2D.AddDepthData,
                AddIntensityData = Pilot2D.AddIntensityData,
                ClearAllPoints = Pilot2D.ClearAllPoints,
                RefreshPilot2D = Pilot2D.RefreshPilot2D,
                SetImageSize = Pilot2D.SetImageSize,
            };
            // 初始化3D显示函数
            _func3d = new VTK3D_FUNC
            {
                AddZAPoints = PHM6000Profiler.AddZAPoints,
                ClearPCLPoints = PHM6000Profiler.ClearPCLPoints,
                GetPointCloudBound = PHM6000Profiler.GetPointCloudBound,
                RenderPCLWindow = PHM6000Profiler.RenderPCLWindow,
                SetLookUpTableRange = PHM6000Profiler.SetLookUpTableRange,
                ShowCubeAxes = PHM6000Profiler.ShowCubeAxes,
                ShowLookUpTable = PHM6000Profiler.ShowLookUpTable,
                UpdatePCLPointColors = PHM6000Profiler.UpdatePCLPointColors,
            };
        }
        #region ICamera Implementation
        public override bool InitDevice(string sn, object handle = null)
        {
            // 如果已连接,仅检查是否需要更新显示句柄
            if (_isConnected && _cameraHandle != IntPtr.Zero)
            {
                if (handle != null && handle is IntPtr hPtr && hPtr != IntPtr.Zero)
                {
                    // 销毁旧的显示句柄
                    if (_lightPic != IntPtr.Zero)
                    {
                        Pilot2D.ClearAllPoints(_lightPic);
                        Pilot2D.DestroyPilot2DEntry(_lightPic);
                    }
                    // 创建新的显示句柄
                    _lightPic = Pilot2D.CreatePilot2DEntry(hPtr);
                    if (_lightPic != IntPtr.Zero)
                    {
                        var config = GetSensorConfig();
                        Pilot2D.SetImageSize(_lightPic, 4096, config.ScanLineCount > 0 ? config.ScanLineCount : 5000);
                        // 更新相机绑定的显示句柄
                        PHM6000Profiler.SetShowHandles(_cameraHandle, _lightPic, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                        AsyncLogHelper.Info($"LBCamera[{SN}]: Display handle updated");
                    }
                }
                return true;
            }
            IntPtr tempHandle = IntPtr.Zero;
            try
            {
@@ -125,14 +197,41 @@
                    // 加载相机当前参数到 _sensorConfig
                    SyncConfigFromCamera();
                    // 创建亮度图显示句柄(类似LLSystem示例)
                    IntPtr hPtr = IntPtr.Zero;
                    if (handle is IntPtr p) hPtr = p;
                    if (hPtr != IntPtr.Zero)
                    {
                        _lightPic = Pilot2D.CreatePilot2DEntry(hPtr);
                        if (_lightPic != IntPtr.Zero)
                        {
                            // 设置图像尺寸,宽度4096,高度根据配置
                            var config = GetSensorConfig();
                            Pilot2D.SetImageSize(_lightPic, 4096, config.ScanLineCount > 0 ? config.ScanLineCount : 5000);
                        }
                    }
                    // 初始化回调
                    _acquisitionCallback = new AcquisitionCallbackZA(OnLineReceived);
                    _acquisitionCompletedCallback = new AcquisitionCompletedCallback(OnAcquisitionCompleted);
                    
                    //PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, _acquisitionCallback, IntPtr.Zero);
                    // 注册采集完成回调(类似LLSystem示例)
                    PHM6000Profiler.RegisterAcquisitionCompletedCallback(_cameraHandle, _acquisitionCompletedCallback, IntPtr.Zero);
                    // 设置2D和3D显示函数(类似LLSystem示例)
                    PHM6000Profiler.SetPilot2dFunc(_cameraHandle, _func2d);
                    PHM6000Profiler.SetVTK3dFunc(_cameraHandle, _func3d);
                    // 设置显示句柄(类似LLSystem示例的SetShowHandles)
                    PHM6000Profiler.SetShowHandles(_cameraHandle, _lightPic, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                    AsyncLogHelper.Info($"LBCamera[{SN}]: Connected and initialized successfully with SDK auto-display mode");
                    return true;
                }
                else
                {
                    AsyncLogHelper.Error($"LBCamera[{SN}]: ConnectToCamera failed, result={result}");
                }
            }
            catch (Exception ex) 
@@ -148,9 +247,20 @@
            if (_isConnected && _cameraHandle != IntPtr.Zero)
            {
                StopGrabbing();
                // 销毁显示句柄
                if (_lightPic != IntPtr.Zero)
                {
                    Pilot2D.ClearAllPoints(_lightPic);
                    Pilot2D.DestroyPilot2DEntry(_lightPic);
                    _lightPic = IntPtr.Zero;
                }
                PHM6000Profiler.DestroyCameraEntry(_cameraHandle);
                _cameraHandle = IntPtr.Zero;
                _isConnected = false;
                AsyncLogHelper.Info($"LBCamera[{SN}]: Closed and cleaned up");
            }
            return true;
        }
@@ -194,79 +304,90 @@
            return cameraList;
        }
        public override bool StartGrabbing()
        private void InitBuffer()
        {
            if (!_isConnected) return false;
            lock (_bufferLock)
            lock (_bitmapLock)
            {
                _lineDataBuffer.Clear();
                _currentBitmapHeight = _sensorConfig.ScanLineCount > 0 ? _sensorConfig.ScanLineCount : 5000;
                // 宽度暂时未知,将在第一行数据到达时初始化
                _currentBitmapWidth = 0;
                if (_currentBitmap != null)
                {
                    _currentBitmap.Dispose();
                    _currentBitmap = null;
                }
                _rawPixelBuffer = null;
                _currentLineCount = 0;
            }
        }
            // 禁用行回调
            PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, IntPtr.Zero, IntPtr.Zero);
            // 设置采集模式:1=扫描模式,1=连续模式
            PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 1);
            int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
            if (result == 0)
            {
                isGrabbing = true;
                return true;
            }
            return false;
        public override bool StartGrabbing()
        {
            // 线扫相机默认使用连续采集模式
            // 参考LLSystem示例的ContinuousScan方法:SetAcquisitionMode(1, 1)
            return StartSingleGrab();
        }
        /// <summary>
        /// 单次采集模式(适用于线扫相机)
        /// 设置采集模式为扫描模式,单次触发
        /// 参考LLSystem示例的StartScan方法:SetAcquisitionMode(1, 0)
        /// 使用SDK自动显示模式,不手动处理数据
        /// </summary>
        public bool StartSingleGrab()
        {
            if (!_isConnected) return false;
            lock (_bufferLock)
            {
                _lineDataBuffer.Clear();
                _currentLineCount = 0;
            }
            // 禁用行回调(与示例一致)
            AsyncLogHelper.Info($"LBCamera[{SN}]: Starting single grab mode");
            // 使用SDK自动显示模式,类似LLSystem示例
            // 不设置AcquisitionCallbackZA,让SDK自动处理图像显示
            PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, IntPtr.Zero, IntPtr.Zero);
            // 设置采集模式:1=扫描模式,0=单次模式
            // 设置采集模式:1=扫描模式,0=单次模式(与LLSystem示例保持一致)
            PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 0);
            int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
            if (result == 0)
            {
                isGrabbing = true;
                AsyncLogHelper.Info($"LBCamera[{SN}]: Single grab started successfully");
                return true;
            }
            else
            {
                AsyncLogHelper.Error($"LBCamera[{SN}]: Failed to start single grab, result={result}");
            }
            return false;
        }
        /// <summary>
        /// 连续采集模式(适用于线扫相机)
        /// 设置采集模式为扫描模式,连续触发
        /// 参考LLSystem示例的ContinuousScan方法:SetAcquisitionMode(1, 1)
        /// 使用SDK自动显示模式,不手动处理数据
        /// </summary>
        public bool StartContinuousGrab()
        public override bool StartContinuousGrab()
        {
            if (!_isConnected) return false;
            lock (_bufferLock)
            {
                _lineDataBuffer.Clear();
                _currentLineCount = 0;
            }
            // 禁用行回调(与示例一致)
            AsyncLogHelper.Info($"LBCamera[{SN}]: Starting continuous grab mode");
            // 使用SDK自动显示模式,类似LLSystem示例
            // 不设置AcquisitionCallbackZA,让SDK自动处理图像显示
            PHM6000Profiler.SetAcquisitionCallbackZA(_cameraHandle, IntPtr.Zero, IntPtr.Zero);
            // 设置采集模式:1=扫描模式,1=连续模式
            // 设置采集模式:1=扫描模式,1=连续模式(与LLSystem示例保持一致)
            PHM6000Profiler.SetAcquisitionMode(_cameraHandle, 1, 1);
            int result = PHM6000Profiler.StartAcquisition(_cameraHandle, 0, 0, 0.0);
            if (result == 0)
            {
                isGrabbing = true;
                AsyncLogHelper.Info($"LBCamera[{SN}]: Continuous grab started successfully");
                return true;
            }
            else
            {
                AsyncLogHelper.Error($"LBCamera[{SN}]: Failed to start continuous grab, result={result}");
            }
            return false;
        }
@@ -279,17 +400,20 @@
            return true;
        }
        public override bool StartWith_SoftTriggerModel()
        {
            // 对于LBCamera(线扫相机),软件触发连续采集使用连续采集模式
            // 对于LBCamera(线扫相机),软件触发连续采集
            // 参考LLSystem示例的ContinuousScan方法:SetAcquisitionMode(1, 1)
            return StartContinuousGrab();
        }
        public override bool StartWith_HardTriggerModel(TriggerSource hardtriggeritem = TriggerSource.Line0)
        {
            // 对于LBCamera(线扫相机),硬件触发也使用连续采集模式
            // 参考LLSystem示例的ContinuousScan方法:SetAcquisitionMode(1, 1)
            // 外部硬件信号会触发相机开始采集
            return StartContinuousGrab();
            return StartSingleGrab();
        }
        public override bool SoftTrigger()
@@ -328,35 +452,38 @@
            bitmap = null;
            if (!_isConnected) return false;
            // 对于线扫相机,使用SDK自动显示模式
            // 注意:SDK自动显示模式下,我们无法直接获取Bitmap
            // 但SDK会自动将图像显示到_lightPic句柄对应的控件上
            // 我们只需要启动单次采集,等待采集完成即可
            using (AutoResetEvent waitHandle = new AutoResetEvent(false))
            {
                Bitmap captured = null;
                bool captured = false;
                EventHandler<CameraEventArgs> handler = (s, e) =>
                {
                    try
                    // 对于线扫相机,仅当IsComplete为true时才表示采集完成
                    if (e is LBCameraEventArgs args && args.IsComplete)
                    {
                        if (e.Bitmap != null)
                        {
                            captured = e.Bitmap.Clone() as Bitmap;
                        }
                        captured = true;
                        waitHandle.Set();
                    }
                    catch (Exception ex)
                    {
                        AsyncLogHelper.Error($"LBCamera: GetImageWithSoftTrigger clone error - {ex.Message}");
                    }
                    waitHandle.Set();
                };
                this.ImageGrabbed += handler;
                try
                {
                    // 使用单次采集模式(与LLSystem示例保持一致)
                    if (StartSingleGrab())
                    {
                        // 等待采集完成
                        if (waitHandle.WaitOne(outtime))
                        {
                            bitmap = captured;
                            return bitmap != null;
                            // 由于SDK自动显示,我们无法返回Bitmap
                            // 但采集已完成,图像已显示到界面上
                            bitmap = null;  // SDK自动显示模式下不返回Bitmap
                            return captured;
                        }
                    }
                }
@@ -378,121 +505,57 @@
        public void UpdateSensorConfig(PHM6000SensorConfig config)
        {
            _sensorConfig = config;
            // 简单示例:设置曝光和增益
            SetExpouseTime(config.ExposureTime);
            SetGain((double)config.AnalogGain);
            // 更多参数同步逻辑应在此处实现
            if (!_isConnected) return;
            // 基础图像参数
            SetParam(EnumNameId.ExposureTime, (float)config.ExposureTime);
            SetParam(EnumNameId.AnalogGain, (float)config.AnalogGain);
            // 扫描控制参数 - 决定单次采集的数据量
            PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.ScanLineCount, config.ScanLineCount, 0, 0);
            // 触发设置 - 决定采集速度
            PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.LineScanTriggerSource, 0, 0, (int)config.LineScanTriggerSource);
            PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.DataAcquisitionTriggerSource, 0, 0, (int)config.DataAcquisitionTriggerSource);
            // 如果是软触发(固定频率),设置频率
            if (config.LineScanTriggerSource == EnumLineScanTriggerSource.固定频率)
            {
                PHM6000Profiler.SetProfilerParameter(_cameraHandle, (int)EnumNameId.SoftwareTriggerRate, 0, config.SoftwareTriggerRate, 0);
            }
            // 确保参数生效
            PHM6000Profiler.SaveAllParametersToDevice(_cameraHandle);
        }
        #endregion
        #endregion
        #region Private Callback & Helpers
        private void OnLineReceived(IntPtr pInstance, IntPtr buffer, int points)
        {
                // 实时回调处理:累积行数据
                if (!isGrabbing) return;
                int lineSize = points * Marshal.SizeOf(typeof(LBPointZA));
                byte[] lineData = new byte[lineSize];
                Marshal.Copy(buffer, lineData, 0, lineSize);
                lock (_bufferLock)
                {
                    _lineDataBuffer.Add(lineData);
                    _currentLineCount++;
                }
        }
        private void OnAcquisitionCompleted(IntPtr pInstance, int nOption)
        {
                // 根据SDK文档:nOption为0时表示一批数据结束,为1时表示全部采集完成
                // 为了兼容性,也处理nOption == 2(点云就绪)
                // 此时使用主动获取方式替代可能会导致crash的GenerateIntensityMap
                if (nOption == 0 || nOption == 1 || nOption == 2)
                {
                    RetrieveDataAndGenerateImage();
                }
        }
            // nOption含义:
            // 0 = 一批数据结束
            // 1 = 全部采集完成(仅单次模式)
            // 2 = 对应数据处理完成(每次采集完成都会触发)
        private void RetrieveDataAndGenerateImage()
        {
            if (_cameraHandle == IntPtr.Zero) return;
            // 记录回调信息
            AsyncLogHelper.Info($"LBCamera[{SN}]: OnAcquisitionCompleted called, nOption={nOption}");
            try
            if (nOption == 2)
            {
                List<byte[]> lineBuffers = new List<byte[]>();
                ulong index = 0;
                IntPtr ptr = IntPtr.Zero;
                // 连续采集模式下,每完成一帧SDK都会自动继续采集下一帧
                // SDK会自动处理图像显示到_lightPic句柄
                // 我们只需要统计采集次数
                _frameCount++;
                // 像示例一样通过索引获取行数据
                while ((ptr = PHM6000Profiler.GetLineDataByIndex(_cameraHandle, index)) != IntPtr.Zero)
                {
                    try
                    {
                        LBLineDataZA lineData = PHM6000Profiler.ConvertToLBLineDataZA(ptr);
                        // 提取强度数据 (Alpha通道)
                        if (lineData.data != null && lineData.data.Length > 0)
                        {
                            int lineWidth = lineData.data.Length;
                            byte[] intensityLine = new byte[lineWidth];
                            for (int i = 0; i < lineWidth; i++)
                            {
                                intensityLine[i] = lineData.data[i].alpha;
                            }
                            lineBuffers.Add(intensityLine);
                        }
                    }
                    catch (Exception ex)
                    {
                        // 忽略单行转换错误
                    }
                    index++;
                }
                AsyncLogHelper.Info($"LBCamera[{SN}]: Frame {_frameCount} completed (continuous mode, SDK auto-display)");
                if (lineBuffers.Count == 0) return;
                int height = lineBuffers.Count;
                int width = lineBuffers[0].Length;
                if (width <= 0 || height <= 0) return;
                Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
                // 设置灰度调色板
                ColorPalette palette = bmp.Palette;
                for (int i = 0; i < 256; i++) palette.Entries[i] = Color.FromArgb(i, i, i);
                bmp.Palette = palette;
                BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                try
                {
                    int stride = bmpData.Stride;
                    IntPtr scan0 = bmpData.Scan0;
                    for (int y = 0; y < height; y++)
                    {
                        if (lineBuffers[y].Length == width) // 确保宽度一致
                        {
                            Marshal.Copy(lineBuffers[y], 0, scan0 + y * stride, width);
                        }
                    }
                }
                finally
                {
                    bmp.UnlockBits(bmpData);
                }
                // 触发事件通知 UI 更新亮度图
                ImageGrabbed?.Invoke(this, new CameraEventArgs(SN, bmp));
            }
            catch (Exception ex)
            {
                AsyncLogHelper.Error($"LBCamera: 生成图像异常 - {ex.Message}");
                // 触发事件通知UI更新(但不传递Bitmap,因为SDK自动显示)
                ImageGrabbed?.Invoke(this, new LBCameraEventArgs(SN, null, true));
            }
        }
@@ -527,7 +590,6 @@
            }
            return false;
        }
        #endregion
    }
}