C++实现查找连通域

目录

一、概述

1.1、四连通域算法

1.2、八连通域算法

1.3、种子填充法

二、代码


一、概述

图像处理中,查找连通域的算法是图像分割的重要方法之一。它能够将一幅图像分成若干个不重叠的区域,每个区域内部像素具有相似的性质,而不同区域之间的像素性质有明显的差异。在实际应用中,查找连通域的算法被广泛应用于数字图像处理、计算机视觉、医学影像分析等领域。

1.1、四连通域算法

四连通域算法是一种基于4邻域搜索的连通域查找算法。该算法认为每个像素与其上下左右四个相邻像素属于同一个连通域。具体步骤如下:

  1. 初始化:选择一个起始点作为种子点,将其标记为已访问;
  2. 搜索:从当前种子点出发,依次搜索其4邻域内的像素点,若该像素点未被访问过,则将其标记为已访问,并将其加入当前连通域;
  3. 更新:将当前连通域内的所有像素点的标签值更新为与种子点相同的标签值;
  4. 重复步骤2和3,直到所有像素点都被访问过。

四连通域算法简单直观,但容易产生过分割的问题。为了解决这个问题,可以采用八连通域算法。

1.2、八连通域算法

八连通域算法是一种基于8邻域搜索的连通域查找算法。该算法认为每个像素与其上下左右以及四个对角线方向上的相邻像素属于同一个连通域。具体步骤与四连通域算法类似,只是在搜索过程中需要考虑更多的相邻像素。

八连通域算法相对于四连通域算法来说,能够更好地避免过分割的问题,但计算量较大。因此,在实际应用中需要根据具体情况选择合适的算法。

1.3、种子填充法

种子填充法是一种基于种子点的连通域查找算法。它首先选择一个或多个种子点作为起始点,然后根据一定的规则(如颜色相似性)向周围扩展,直到所有满足条件的像素都被加入同一连通域。具体步骤如下:

  1. 初始化:选择一个或多个种子点作为起始点,将其标记为已访问;
  2. 搜索:从当前种子点出发,依次搜索其8邻域内的像素点,若该像素点未被访问过且满足条件(如颜色相似),则将其标记为已访问,并将其加入当前连通域;
  3. 更新:将当前连通域内的所有像素点的标签值更新为与种子点相同的标签值;
  4. 重复步骤2和3,直到所有像素点都被访问过。

种子填充法具有较强的灵活性和适应性,可以根据实际需求选择不同的起始点和扩展规则。但容易受到噪声的影响,因此在实际应用中需要进行预处理和后处理。

综上所述,查找连通域的算法是图像处理中的重要方法之一。不同的算法适用于不同的场景和需求,需要根据具体情况进行选择和应用。

二、代码

以下代码依赖opencv读取图片,仅此而已。代码中算法是基于种子填充算法实现,其实还有形成编码法,在不同上下文环境,算法性能不同。例如:图片连通域数量巨大,每个连通区域面积很小,可能形成编码法效率更高。这里把原图丢出来:

以下是完整代码:

cpp 复制代码
#include <opencv2\opencv.hpp>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
using namespace cv;

typedef struct _Feather
{
    int label;              // 连通域的label值
    int area;               // 连通域的面积
    Rect boundingbox;       // 连通域的外接矩形框
} Feather;

/*
Input:src: 待检测连通域的二值化图像
Output:dst: 标记后的图像 featherList: 连通域特征的清单
return:
连通域数量。
*/
int bwLabel(Mat& src, Mat& dst, vector<Feather>& featherList)
{
    int rows = src.rows;
    int cols = src.cols;
    int labelValue = 0;
    Point seed, neighbor;
    stack<Point> pointStack;    // 堆栈
    int area = 0;               // 用于计算连通域的面积
    int leftBoundary = 0;       // 连通域的左边界,即外接最小矩形的左边框,横坐标值,依此类推
    int rightBoundary = 0;
    int topBoundary = 0;
    int bottomBoundary = 0;
    Rect box;                   // 外接矩形框
    Feather feather;
    featherList.clear();    // 清除数组
    dst.release();
    dst = src.clone();
    for (int i = 0; i < rows; i++)
    {
        uchar* pRow = dst.ptr<uchar>(i);
        for (int j = 0; j < cols; j++)
        {
            //【注:一旦连通域赋值为1;遍历当前行的下一行时候,就会自动跳过下面if判断】
            if (pRow[j] == 255)
            {
                area = 0;
                labelValue++;           // labelValue最大为254,最小为1.
                seed = Point(j, i); //(731,49)    // Point(横坐标,纵坐标)(x,y)
                                    //int p = dst.ptr<uchar>(i)[j];
                dst.at<uchar>(seed) = labelValue;//1
                pointStack.push(seed);//坐标压栈
                area++;
                leftBoundary = seed.x;//731
                rightBoundary = seed.x;//731
                topBoundary = seed.y;//49
                bottomBoundary = seed.y;//49
                while (!pointStack.empty())
                {
                    //<1>右邻像素点
                    neighbor = Point(seed.x + 1, seed.y);
                    if ((seed.x != (cols - 1)) && (dst.at<uchar>(neighbor) == 255))
                    {
                        dst.at<uchar>(neighbor) = labelValue;//【注:】赋值便签1,保证不走回头路和分类连通域
                        pointStack.push(neighbor);

                        area++;
                        if (rightBoundary < neighbor.x)//更新边界
                            rightBoundary = neighbor.x;
                    }
                    //<2>下邻像素点
                    neighbor = Point(seed.x, seed.y + 1);
                    if ((seed.y != (rows - 1)) && (dst.at<uchar>(neighbor) == 255))
                    {
                        dst.at<uchar>(neighbor) = labelValue;
                        pointStack.push(neighbor);

                        area++;
                        if (bottomBoundary < neighbor.y)
                            bottomBoundary = neighbor.y;
                    }
                    //<3>左邻像素点
                    neighbor = Point(seed.x - 1, seed.y);
                    //int testx = seed.x;
                    //int testp = dst.at<uchar>(neighbor);
                    if ((seed.x != 0) && (dst.at<uchar>(neighbor) == 255))
                    {
                        dst.at<uchar>(neighbor) = labelValue;
                        pointStack.push(neighbor);
                        area++;
                        if (leftBoundary > neighbor.x)
                            leftBoundary = neighbor.x;
                    }
                    //<4>上邻边界点
                    neighbor = Point(seed.x, seed.y - 1);
                    if ((seed.y != 0) && (dst.at<uchar>(neighbor) == 255))
                    {
                        dst.at<uchar>(neighbor) = labelValue;
                        pointStack.push(neighbor);
                        area++;
                        if (topBoundary > neighbor.y)
                            topBoundary = neighbor.y;
                    }
                    seed = pointStack.top();
                    pointStack.pop();
                }
                box = Rect(leftBoundary, topBoundary, rightBoundary - leftBoundary, bottomBoundary - topBoundary);
                rectangle(src, box, 255);
                feather.area = area;
                feather.boundingbox = box;
                feather.label = labelValue;
                featherList.push_back(feather);
            }
        }
    }
    return labelValue;
}

int main(int argc, char* argv[])
{
    Mat src(imread("d:/Data/123.png", 0));
    if (src.empty())
        exit(-1);
    threshold(src, src, 127, 255, THRESH_BINARY);   // 二值化图像
    vector<Feather> featherList;                    // 存放连通域特征
    Mat dst;
    cout << "连通域数量: " << bwLabel(src, dst, featherList) << endl;
    // 为了方便观察,可以将label"放大"
    for (int i = 0; i < dst.rows; i++)
    {
        uchar* p = dst.ptr<uchar>(i);
        for (int j = 0; j < dst.cols; j++)
        {
            p[j] = 30 * p[j];
        }
    }
    cout << "标号" << "\t" << "面积" << endl;
    for (vector<Feather>::iterator it = featherList.begin(); it < featherList.end(); it++)
    {
        cout << it->label << "\t" << it->area << endl;
        rectangle(dst, it->boundingbox, 255);
    }
    cv::namedWindow("dst");
    imshow("src", src);
    imshow("dst", dst);
    waitKey();
    destroyAllWindows();
    system("pause");
    return 0;
}

执行之后的效果图:

相关推荐
骊城英雄6 分钟前
Rust从入门到精通-trait
人工智能·算法·rust
阿文和她的Key9 分钟前
GPT-5.6 降价后, API 账单的三层漏斗该怎么拆
人工智能·gpt·ai·chatgpt
BEOL贝尔科技23 分钟前
样本安全存储中还有哪些重要因素需要考虑?如何设置样本安全?
人工智能·安全·数据分析
可编程芯片开发40 分钟前
基于PI控制算法的pwm直流电机控制系统Simulink建模与仿真
算法
小王C语言43 分钟前
【8.进行接口测试】:通过 curl 进行接口自动化测试 / 通过 python 程序进行接口自动化测试
网络·c++
thesky1234561 小时前
27届大模型岗面试准备(十四):多模态大模型 VLM——从视觉编码器到多模态推理的完整链路
人工智能·ai·大模型
一根数据线1 小时前
BIM建模效率低?试试和AI工具配合使用
人工智能·ai·3d建模·3d模型·bim·ai建模·造形家
怕浪猫1 小时前
2840亿参数只卖白菜价:DeepSeek V4 Flash 正式版上线,Agent 能力暴涨6倍
人工智能·算法
不爱记笔记1 小时前
多模态AI如何理解视频内容?从视觉、语音到语义的三层技术拆解
人工智能·自然语言处理·nlp·音视频·多模态
让学习成为一种生活方式1 小时前
苄基异喹啉生物碱糖基转移酶UGT74AN1晶体--Journal of Agricultural and Food Chemistry
人工智能·算法