找回密码
 立即注册
首页 业界区 业界 OpenCVSharp:学习连通性检测的使用

OpenCVSharp:学习连通性检测的使用

颜清华 9 小时前
连通性检测

连通性检测是计算机视觉中的一种基础图像处理技术,用于识别和标记二值图像中相互连接的像素区域。简单来说,它能够找出图像中所有独立的"连通区域"(即像素之间相互连接形成的区域)。
应用场景
更多的是其它图像处理的一个前置步骤,可能有时候可以用来统计物体数量,但是使用场景很有限。
效果
1.png

2.png

实践

图像灰度化
首先需要将图像转化为灰度图:
  1. // 转换为灰度图像
  2. using var gray = src.CvtColor(ColorConversionCodes.BGR2GRAY);
复制代码
灰度图是一种只包含亮度信息而不包含颜色信息的图像表示方式,它将彩色图像中的每个像素转换为从黑色(最暗)到白色(最亮)的256个灰度级别中的一个值,通常用0-255的数值来表示,其中0代表纯黑色,255代表纯白色,中间值代表不同深浅的灰色。
图像二值化
然后再将灰度图转化为二值图像:
  1. // 二值化处理
  2. using var binary = new Mat();
  3. ThresholdTypes thresholdType = GetThresholdType();
  4. if (ThresholdType == "Adaptive")
  5. {
  6.      Cv2.AdaptiveThreshold(gray, binary, 255, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 11, 2);
  7. }
  8. else
  9. {
  10.      Cv2.Threshold(gray, binary, ThresholdValue, 255, thresholdType);
  11. }
  12. private ThresholdTypes GetThresholdType()
  13. {
  14.      return ThresholdType switch
  15.      {
  16.          "Otsu" => ThresholdTypes.Otsu,
  17.          "Binary" => ThresholdTypes.Binary,
  18.          _ => ThresholdTypes.Otsu
  19.      };
  20. }
复制代码
这里展示了OpenCVSharp中进行图像二值化的两种方法,分别是Cv2.AdaptiveThreshold与Cv2.Threshold。
先来看下Cv2.AdaptiveThreshold:
  1. public static void AdaptiveThreshold(InputArray src, OutputArray dst,
  2.     double maxValue, AdaptiveThresholdTypes adaptiveMethod, ThresholdTypes thresholdType, int blockSize, double c)
  3. {
  4.     if (src is null)
  5.         throw new ArgumentNullException(nameof(src));
  6.     if (dst is null)
  7.         throw new ArgumentNullException(nameof(dst));
  8.     src.ThrowIfDisposed();
  9.     dst.ThrowIfNotReady();
  10.     NativeMethods.HandleException(
  11.         NativeMethods.imgproc_adaptiveThreshold(src.CvPtr, dst.CvPtr, maxValue, (int) adaptiveMethod, (int)thresholdType, blockSize, c));
  12.     GC.KeepAlive(src);
  13.     GC.KeepAlive(dst);
  14.     dst.Fix();
  15. }
复制代码
AdaptiveThreshold 方法是OpenCV中的一个自适应阈值处理函数,它的主要作用是对图像进行局部自适应的二值化处理。
与全局阈值处理不同,它不是对整个图像使用单一的阈值,而是根据图像中每个像素周围的局部区域动态计算阈值。这种方法特别适用于光照不均匀的图像,能够更好地处理图像中不同区域亮度差异较大的情况。
该方法通过计算每个像素周围邻域的平均值或高斯加权平均值,然后减去一个常数c来得到局部阈值,最后根据这个局部阈值对像素进行二值化。在连通性分析应用中,自适应阈值能够在光照不均匀的情况下产生比全局阈值更好的二值化效果,从而提高连通区域检测的准确性。
看一下这个方法的参数:
参数名含义src源图像,必须是8位单通道图像(通常是灰度图)dst目标图像,与源图像具有相同的大小和类型maxValue满足条件的像素被赋予的非零值(通常是255)adaptiveMethod自适应阈值算法:ADAPTIVE_THRESH_MEAN_C(局部平均值)或 ADAPTIVE_THRESH_GAUSSIAN_C(高斯加权平均值)thresholdType阈值类型,必须是 THRESH_BINARY 或 THRESH_BINARY_INVblockSize用于计算阈值的像素邻域大小,必须是奇数(如3, 5, 7等)c从平均值或加权平均值中减去的常数,可以是正数、零或负数再看一下AdaptiveThresholdTypes:
枚举值数值描述计算方式MeanC0均值自适应阈值计算block_size × block_size像素邻域的均值,然后减去param1GaussianC1高斯加权自适应阈值计算block_size × block_size像素邻域的高斯加权和,然后减去param1再来看下Cv2.Threshold:
  1. public static double Threshold(InputArray src, OutputArray dst, double thresh, double maxval, ThresholdTypes type)
  2. {
  3.     if (src is null)
  4.         throw new ArgumentNullException(nameof(src));
  5.     if (dst is null)
  6.         throw new ArgumentNullException(nameof(dst));
  7.     src.ThrowIfDisposed();
  8.     dst.ThrowIfNotReady();
  9.     NativeMethods.HandleException(
  10.         NativeMethods.imgproc_threshold(src.CvPtr, dst.CvPtr, thresh, maxval, (int)type, out var ret));
  11.     GC.KeepAlive(src);
  12.     GC.KeepAlive(dst);
  13.     dst.Fix();
  14.     return ret;
  15. }
复制代码
Threshold 方法对输入图像的每个像素应用固定级别的阈值处理,将灰度图像转换为二值图像或进行其他类型的阈值变换。这是图像处理中的基本操作,常用于图像分割、特征提取等场景。
看一下这个方法的参数:
参数名类型含义srcInputArray输入数组(单通道,8位或32位浮点类型)dstOutputArray输出数组,与src具有相同的大小和类型threshdouble阈值,用于判断像素值的分界点maxvaldouble最大值,用于THRESH_BINARY和THRESH_BINARY_INV阈值类型typeThresholdTypes阈值类型,决定了如何应用阈值再看一下阈值类型:
枚举值数值描述计算公式Binary0二值化阈值src(x,y) > thresh ? maxval : 0BinaryInv1反向二值化阈值src(x,y) > thresh ? 0 : maxvalTrunc2截断阈值src(x,y) > thresh ? thresh : src(x,y)Tozero3零化阈值src(x,y) > thresh ? src(x,y) : 0TozeroInv4反向零化阈值src(x,y) > thresh ? 0 : src(x,y)Mask7掩码值-Otsu8使用Otsu算法自动选择最佳阈值自动计算最优阈值Triangle16使用Triangle算法自动选择最佳阈值自动计算最优阈值比较常用的就是Binary与Otsu。
连通性检测
在OpenCVSharp中对二值图像进行连通性分析一行代码就行:
  1. // 连通性分析
  2. var cc = Cv2.ConnectedComponentsEx(binary);
复制代码
现在看下Cv2.ConnectedComponentsEx:
  1. public static ConnectedComponents ConnectedComponentsEx(
  2.      InputArray image,
  3.      PixelConnectivity connectivity = PixelConnectivity.Connectivity8,
  4.      ConnectedComponentsAlgorithmsTypes ccltype = ConnectedComponentsAlgorithmsTypes.Default)
  5. {
  6.      using var labelsMat = new Mat<int>();
  7.      using var statsMat = new Mat<int>();
  8.      using var centroidsMat = new Mat<double>();
  9.      var nLabels = ConnectedComponentsWithStatsWithAlgorithm(
  10.          image, labelsMat, statsMat, centroidsMat, connectivity, MatType.CV_32S, ccltype);
  11.      var labels = labelsMat.ToRectangularArray();
  12.      var stats = statsMat.ToRectangularArray();
  13.      var centroids = centroidsMat.ToRectangularArray();
  14.      var blobs = new ConnectedComponents.Blob[nLabels];
  15.      for (var i = 0; i < nLabels; i++)
  16.      {
  17.          blobs[i] = new ConnectedComponents.Blob
  18.          {
  19.              Label = i,
  20.              Left = stats[i, 0],
  21.              Top = stats[i, 1],
  22.              Width = stats[i, 2],
  23.              Height = stats[i, 3],
  24.              Area = stats[i, 4],
  25.              Centroid = new Point2d(centroids[i, 0], centroids[i, 1]),
  26.          };
  27.      }
  28.      return new ConnectedComponents(blobs, labels, nLabels);
  29. }
复制代码
ConnectedComponentsEx 函数计算布尔图像的连通组件标记图像,支持4邻域或8邻域连通性。它返回一个包含所有标记信息的结构化对象,其中标签0代表背景,其他标签[1, N-1]代表不同的前景连通区域。
参数名含义image需要进行标记的输入图像,通常是二值图像connectivity连通性类型,默认为8邻域连通。Connectivity8表示8邻域连通(上下左右+对角线),Connectivity4表示4邻域连通(仅上下左右)ccltype连通组件算法类型,默认为Default。指定用于连通组件分析的算法现在我们得到了很多区域:
3.png

现在我们想将所有检测到的连通区域(blobs)以不同颜色渲染到目标图像上。
  1. // 创建标签图像
  2. using var labelView = src.EmptyClone();
  3. cc.RenderBlobs(labelView);
  4. public void RenderBlobs(Mat img)
  5. {
  6.      if (img is null)
  7.          throw new ArgumentNullException(nameof(img));
  8.      /*
  9.      if (img.Empty())
  10.          throw new ArgumentException("img is empty");
  11.      if (img.Type() != MatType.CV_8UC3)
  12.          throw new ArgumentException("img must be CV_8UC3");*/
  13.      if (Blobs is null || Blobs.Count == 0)
  14.          throw new OpenCvSharpException("Blobs is empty");
  15.      if (Labels is null)
  16.          throw new OpenCvSharpException("Labels is empty");
  17.      var height = Labels.GetLength(0);
  18.      var width = Labels.GetLength(1);
  19.      img.Create(new Size(width, height), MatType.CV_8UC3);
  20.      var colors = new Scalar[Blobs.Count];
  21.      colors[0] = Scalar.All(0);
  22.      for (var i = 1; i < Blobs.Count; i++)
  23.      {
  24.          colors[i] = Scalar.RandomColor();
  25.      }
  26.      using var imgt = new Mat<Vec3b>(img);
  27.      var indexer = imgt.GetIndexer();
  28.      for (var y = 0; y < height; y++)
  29.      {
  30.          for (var x = 0; x < width; x++)
  31.          {
  32.              var labelValue = Labels[y, x];
  33.              indexer[y, x] = colors[labelValue].ToVec3b();
  34.          }
  35.      }
  36. }
复制代码
这个函数是 ConnectedComponents 类的一个方法,用于将所有检测到的连通区域(blobs)以不同颜色渲染到目标图像上。
RenderBlobs 方法将连通组件分析的结果可视化,为每个不同的连通区域分配一个随机颜色,并将这些区域绘制到指定的目标图像中。
创建边界框图像:
  1. // 创建边界框图像
  2. using var rectView = binary.CvtColor(ColorConversionCodes.GRAY2BGR);
  3. foreach (var blob in cc.Blobs.Skip(1))
  4. {
  5.     rectView.Rectangle(blob.Rect, Scalar.Red);
  6. }
复制代码
获取最大连通区域:
  1. // 获取最大连通区域
  2. var maxBlob = cc.GetLargestBlob();
  3. using var filtered = new Mat();
  4. cc.FilterByBlob(src, filtered, maxBlob);
复制代码
增加点击显示大图功能
为了更好查看效果,可以增加一个点击显示大图功能,如下所示:
4.png

1、XAML中的样式定义
在 ConnectedComponentsSampleView.xaml 中定义了一个可点击图片的样式:
  1. [/code]这个样式做了两件事:
  2. 将鼠标悬停时的光标设置为手型,提示用户可以点击
  3. 为 MouseLeftButtonDown 事件绑定处理函数 Image_MouseLeftButtonDown
  4. 2、图片控件应用样式
  5. 所有需要点击查看大图的图片控件都应用了这个样式,例如:
  6. [code]
复制代码
注意这里使用了 Tag 属性来存储图片的标题,用于后续显示大图时的窗口标题。
3、事件处理逻辑
在 ConnectedComponentsSampleView.xaml.cs 中实现了核心的事件处理逻辑:
  1. private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  2. {
  3.     if (sender is Image image && image.Source is BitmapImage bitmapImage)
  4.     {
  5.         // 获取图片标题
  6.         string title = image.Tag as string ?? "图片";
  7.         
  8.         // 创建新窗口显示大图
  9.         Window imageWindow = new Window
  10.         {
  11.             Title = title,
  12.             Width = 800,
  13.             Height = 600,
  14.             WindowStartupLocation = WindowStartupLocation.CenterScreen,
  15.             WindowState = WindowState.Normal
  16.         };
  17.         // 创建Image控件显示图片
  18.         var largeImage = new Image
  19.         {
  20.             Source = bitmapImage,
  21.             Stretch = Stretch.Uniform // 保持原始比例
  22.         };
  23.         // 设置窗口内容
  24.         imageWindow.Content = largeImage;
  25.         
  26.         // 显示窗口
  27.         imageWindow.Show();
  28.     }
  29. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册