Opencv3实现图像分割之最大连通域算法

本文介绍使用OpenCV进行图像二值化处理,并通过轮廓检测找到图像中的最大区域。首先,从文件读取灰度图像,应用Otsu阈值进行二值化。接着,利用findContours函数检测所有轮廓,通过遍历计算各轮廓面积,找出最大轮廓并绘制其边界框。最后,展示所有区域及最大区域的检测结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接 作者:大星小辰


 

#include<opencv2\opencv.hpp>
#include<cmath>

using namespace cv;
using namespace std;

int main()
{
    Mat srcImage = imread( "3.jpg" ,0);
    if( !srcImage.data )
    {
        cout << "读取失败" << endl;
        return 0;
    }
    imshow( "原始图" , srcImage );

    // threshold只针对二值化图像
    threshold( srcImage , srcImage , 0.0 , 255.0 ,CV_THRESH_BINARY|CV_THRESH_OTSU ); 

    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;

    findContours( srcImage , contours , hierarchy , CV_RETR_CCOMP , CV_CHAIN_APPROX_SIMPLE );

    vector<Point> maxcontours ;   //最大轮廓
    double maxArea = 0;

//    vector<vector<Point>>::const_iterator itContours = contours.begin();
    for( size_t i = 0; i < contours.size();i++ )
    {
        double area = contourArea( contours[i] );
        if( area > maxArea )
        {
            maxArea = area;
            maxcontours = contours[i];
        }
    }

    Rect maxRect = boundingRect( maxcontours );  //查找矩形框

    Mat result1 , result2;

    srcImage.copyTo( result1 );
    srcImage.copyTo( result2 );

    for( size_t i = 0; i < contours.size(); i++ )
    {
        Rect r = boundingRect( contours[i] );
        rectangle( result1 , r , Scalar( 255 ) );
    }
    imshow( "all regions" , result1 );
    waitKey();

    rectangle( result2 , maxRect , Scalar( 255 ) );
    imshow( "largest region" , result2 );
    waitKey();
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值