From 219a186529d0513154a7d8ece1a06ca0dcc8460e Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Fri, 31 Jul 2026 17:58:04 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8A=E6=94=BE=E5=9B=BE=E7=89=87=E5=86=85?= =?UTF-8?q?=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PLCSharpWpf/VVMs/Vision/Camera/CameraBase.cs | 30 ++++++++++- .../Vision/Camera/CameraConfigViewModel.cs | 45 ++++++++++------ PLCSharpWpf/VVMs/Vision/Camera/HikCamera.cs | 52 +++++++++++++------ .../VVMs/Vision/VisionConfigViewModel.cs | 49 +++++++++-------- .../Access/ImageFromCameraHandler.cs | 8 ++- PLCSharpWpf/VVMs/Vision/VisionsModel.cs | 1 + PLCSharpWpf/VVMs/Vision/VisionsViewModel.cs | 45 ++++++++++------ 7 files changed, 156 insertions(+), 74 deletions(-) diff --git a/PLCSharpWpf/VVMs/Vision/Camera/CameraBase.cs b/PLCSharpWpf/VVMs/Vision/Camera/CameraBase.cs index 090f25e..ed1dbe5 100644 --- a/PLCSharpWpf/VVMs/Vision/Camera/CameraBase.cs +++ b/PLCSharpWpf/VVMs/Vision/Camera/CameraBase.cs @@ -260,11 +260,37 @@ namespace PLCSharp.VVMs.Vision.Camera return false; } + private readonly object _MatSync = new(); + private Mat _Mat; + /// - /// 图像矩阵 + /// 图像矩阵(最新帧)。注意:getter 返回的是内部共享引用,外部如需长期持有 + /// 或跨线程使用,应调用 获取独立拷贝 /// [NotMapped] - public Mat Mat { get; set; } + public Mat Mat + { + get { lock (_MatSync) { return _Mat; } } + set + { + lock (_MatSync) + { + _Mat?.Dispose(); + _Mat = value; + } + } + } + + /// + /// 获取当前帧的独立拷贝(线程安全,锁内克隆) + /// + public Mat CloneLatestFrame() + { + lock (_MatSync) + { + return _Mat?.Clone(); + } + } /// /// 相机Params diff --git a/PLCSharpWpf/VVMs/Vision/Camera/CameraConfigViewModel.cs b/PLCSharpWpf/VVMs/Vision/Camera/CameraConfigViewModel.cs index e96b32a..9c967bb 100644 --- a/PLCSharpWpf/VVMs/Vision/Camera/CameraConfigViewModel.cs +++ b/PLCSharpWpf/VVMs/Vision/Camera/CameraConfigViewModel.cs @@ -44,21 +44,30 @@ namespace PLCSharp.VVMs.Vision.Camera get { return _ShowMat; } set { - SetProperty(ref _ShowMat, value); - if (value == null) return; - _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() => + var mat = value; + if (mat == null) return; + try { - if (_ImgSrc != null - && _ShowMat.Width == _ImgSrc.PixelWidth - && _ShowMat.Height == _ImgSrc.PixelHeight) + System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { - WriteableBitmapConverter.ToWriteableBitmap(_ShowMat, _ImgSrc); - } - else - { - ImgSrc = _ShowMat.ToWriteableBitmap(); - } - })); + if (_ImgSrc != null + && mat.Width == _ImgSrc.PixelWidth + && mat.Height == _ImgSrc.PixelHeight) + { + WriteableBitmapConverter.ToWriteableBitmap(mat, _ImgSrc); + } + else + { + ImgSrc = mat.ToWriteableBitmap(); + } + })); + } + catch (Exception ex) + { + SendErr($"图像转换失败: {ex.Message}"); + return; + } + SetProperty(ref _ShowMat, value); } } @@ -96,6 +105,8 @@ namespace PLCSharp.VVMs.Vision.Camera public override void OnDialogClosed() { Camera.StopContinuous(); + _ShowMat?.Dispose(); + } private DelegateCommand _StopContinuous; @@ -148,7 +159,9 @@ namespace PLCSharp.VVMs.Vision.Camera case 1: if (Camera.WaitOne(3000)) { - ShowMat = Camera.Mat; + var frame = Camera.CloneLatestFrame(); + ShowMat = frame; + frame?.Dispose(); flow.Step++; } @@ -183,7 +196,9 @@ namespace PLCSharp.VVMs.Vision.Camera case 1: if (Camera.WaitOne(3000)) { - ShowMat = Camera.Mat; + var frame = Camera.CloneLatestFrame(); + ShowMat = frame; + frame?.Dispose(); } if (continuous == false) { diff --git a/PLCSharpWpf/VVMs/Vision/Camera/HikCamera.cs b/PLCSharpWpf/VVMs/Vision/Camera/HikCamera.cs index cb9e3b8..bd3d5d4 100644 --- a/PLCSharpWpf/VVMs/Vision/Camera/HikCamera.cs +++ b/PLCSharpWpf/VVMs/Vision/Camera/HikCamera.cs @@ -124,7 +124,7 @@ namespace PLCSharp.VVMs.Vision.Camera result = Camera.StreamGrabber.StartGrabbing(); if (result != MvError.MV_OK) { - receiveThread.Join(); + receiveThread?.Join(); Log(ShowErrorMsg(result, "Start Grabbing Fail!")); return false; } @@ -158,27 +158,45 @@ namespace PLCSharp.VVMs.Vision.Camera { while (true) { - int result = Camera.StreamGrabber.GetImageBuffer(1000, out frameOut); - if (result == MvError.MV_OK) + try { - var w = (int)frameOut.Image.Width; - var h = (int)frameOut.Image.Height; - - if (HikCameras.IsMonoPixelFormat(frameOut.Image.PixelType)) + int result = Camera.StreamGrabber.GetImageBuffer(1000, out frameOut); + if (result == MvError.MV_OK) { - Mat = Mat.FromPixelData(h, w, MatType.CV_8U, frameOut.Image.PixelDataPtr); - } - else if (HikCameras.IsColorPixelFormat(frameOut.Image.PixelType)) - { - Mat = Mat.FromPixelData(h, w, MatType.CV_8UC3, frameOut.Image.PixelDataPtr); - } + try + { + var w = (int)frameOut.Image.Width; + var h = (int)frameOut.Image.Height; - Camera.StreamGrabber.FreeImageBuffer(frameOut); - _imageReadyEvent.Set(); + if (HikCameras.IsMonoPixelFormat(frameOut.Image.PixelType)) + { + // FromPixelData 是零拷贝浅包装,必须深拷贝后再释放 SDK 缓冲区,否则 Mat 数据悬空(use-after-free) + using var wrap = Mat.FromPixelData(h, w, MatType.CV_8U, frameOut.Image.PixelDataPtr); + Mat = wrap.Clone(); + } + else if (HikCameras.IsColorPixelFormat(frameOut.Image.PixelType)) + { + using var wrap = Mat.FromPixelData(h, w, MatType.CV_8UC3, frameOut.Image.PixelDataPtr); + Mat = wrap.Clone(); + } + } + finally + { + // 无论深拷贝成功与否都必须归还 SDK 缓冲区,否则 SDK 缓冲池耗尽 + Camera.StreamGrabber.FreeImageBuffer(frameOut); + } + _imageReadyEvent.Set(); + } + else + { + Thread.Sleep(1); + } } - else + catch (Exception ex) { - Thread.Sleep(1); + // 单帧处理异常不能杀死采集线程,否则拍照会永久超时 + System.Diagnostics.Debug.WriteLine($"[HikCamera] 采集异常: {ex.Message}"); + Thread.Sleep(10); } } } diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs index bc4aa4d..40a8152 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs @@ -98,6 +98,7 @@ namespace PLCSharp.VVMs.Vision public override void OnDialogClosed() { SelectedVisionFunction.EditImageEdit = null; + _ShowMat?.Dispose(); VisionsModel.Manage.Execute("Save"); } @@ -348,30 +349,32 @@ namespace PLCSharp.VVMs.Vision get { return _ShowMat; } set { - SetProperty(ref _ShowMat, value); - if (value == null) return; - _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() => - { - try - { - if (_ImgSrc != null - && _ShowMat.Width == _ImgSrc.PixelWidth - && _ShowMat.Height == _ImgSrc.PixelHeight - && _ShowMat.Channels() == _ImgSrc.Format.BitsPerPixel / 8 + var mat = value; + if (mat == null) return; + try + { + System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => + { + if (_ImgSrc != null + && mat.Width == _ImgSrc.PixelWidth + && mat.Height == _ImgSrc.PixelHeight + && mat.Channels() == _ImgSrc.Format.BitsPerPixel / 8 ) - { - WriteableBitmapConverter.ToWriteableBitmap(_ShowMat, _ImgSrc); - } - else - { - ImgSrc = WriteableBitmapConverter.ToWriteableBitmap(_ShowMat); - } - } - catch (Exception ex) - { - SendErr($"图像转换失败: {ex.Message}"); - } - })); + { + WriteableBitmapConverter.ToWriteableBitmap(mat, _ImgSrc); + } + else + { + ImgSrc = WriteableBitmapConverter.ToWriteableBitmap(mat); + } + })); + } + catch (Exception ex) + { + SendErr($"图像转换失败: {ex.Message}"); + return; + } + SetProperty(ref _ShowMat, value); } } diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Access/ImageFromCameraHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Access/ImageFromCameraHandler.cs index 6dbf626..db3a4c0 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Access/ImageFromCameraHandler.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Access/ImageFromCameraHandler.cs @@ -45,7 +45,13 @@ if (item.Camera.WaitOne(3000)) { - func.Src = item.Camera.Mat; + // 取独立拷贝,避免相机下一帧覆盖/释放当前 Mat 后,流程继续使用已释放的内存 + var frame = item.Camera.CloneLatestFrame(); + if (frame == null) + { + throw new Exception("未获取到相机图像!"); + } + func.Src = frame; item.Flow.Done = true; item.Flow.Step++; return true; diff --git a/PLCSharpWpf/VVMs/Vision/VisionsModel.cs b/PLCSharpWpf/VVMs/Vision/VisionsModel.cs index f79d5fb..9402e0e 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionsModel.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionsModel.cs @@ -360,6 +360,7 @@ namespace PLCSharp.VVMs.Vision } } _DatasContext.Save(); + if(SelectedCamera!=null) SelectedCamera.Prompt = ""; } diff --git a/PLCSharpWpf/VVMs/Vision/VisionsViewModel.cs b/PLCSharpWpf/VVMs/Vision/VisionsViewModel.cs index cb90396..ac2ad0f 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionsViewModel.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionsViewModel.cs @@ -39,21 +39,30 @@ namespace PLCSharp.VVMs.Vision get { return _ShowMat; } set { + var mat = value; + if (mat == null) return; + try + { + System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => + { + if (_ImgSrc != null + && mat.Width == _ImgSrc.PixelWidth + && mat.Height == _ImgSrc.PixelHeight) + { + WriteableBitmapConverter.ToWriteableBitmap(mat, _ImgSrc); + } + else + { + ImgSrc = mat.ToWriteableBitmap(); + } + })); + } + catch (Exception ex) + { + SendErr($"图像转换失败: {ex.Message}"); + return; + } SetProperty(ref _ShowMat, value); - if (value == null) return; - _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(new Action(() => - { - if (_ImgSrc != null - && _ShowMat.Width == _ImgSrc.PixelWidth - && _ShowMat.Height == _ImgSrc.PixelHeight) - { - WriteableBitmapConverter.ToWriteableBitmap(_ShowMat, _ImgSrc); - } - else - { - ImgSrc = _ShowMat.ToWriteableBitmap(); - } - })); } } @@ -169,7 +178,9 @@ namespace PLCSharp.VVMs.Vision case 1: if (Camera.WaitOne(3000)) { - ShowMat = Camera.Mat; + var frame = Camera.CloneLatestFrame(); + ShowMat = frame; + frame?.Dispose(); flow.Step++; } @@ -204,7 +215,9 @@ namespace PLCSharp.VVMs.Vision case 1: if (Camera.WaitOne(3000)) { - ShowMat = Camera.Mat; + var frame = Camera.CloneLatestFrame(); + ShowMat = frame; + frame?.Dispose(); } if (continuous == false) {