openCV实现图像的轮廓检测以及外接矩形

前两篇博文分别介绍了图像的边缘检测和轮廓检测,本文接着介绍图像的轮廓检测和轮廓外接矩形:

一、代码部分:

// extract_contours.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<cv.h>  
#include<highgui.h>  
using namespace cv;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    //load src image
    string img_name="..\\image_norm\\71253.jpg";
    Mat image=imread(img_name); 
    imshow("src_image",image);
    cvWaitKey(0);
    //convert into gray image
    Mat gray(image.size(),CV_8U);  
    cvtColor(image,gray,CV_BGR2GRAY);
    imshow("gray",gray);
    cvWaitKey(0);
    //convert into bin image
    threshold(gray,gray,128,255,THRESH_BINARY);//转换成2值图像  
    imshow("binary",gray); 
    cvWaitKey(0);
    // Detecting contours 
    vector<vector<Point>> contours;  //定义轮廓集合  
    vector<Vec4i> hierarchy; 
    findContours(gray, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//CV_RETR_EXTERNAL只检测外部轮廓
    // draw black contours on white image  
    Mat result(gray.size(),CV_8U,Scalar(255));  
    int index = 0;  
    for (; index >= 0; index = hierarchy[index][0]) //hierarchy[index][0]表示后一个轮廓
    {  
        Scalar color(rand() & 255, rand() & 255, rand() & 255);  
        drawContours(result, contours, index, Scalar(0), 1, 8, hierarchy);//描绘字符的外轮廓  
        Rect rect = boundingRect(contours[index]);//检测外轮廓  
        rectangle(result, rect, Scalar(0,0,255), 3);//对外轮廓加矩形框  
    }   
     imshow("Contours on white image",result);  
     cvWaitKey(0);
     //draw contours on the original image  
     Mat original=imread(img_name); 
     int index_ori = 0;  
     for (; index_ori >= 0; index_ori = hierarchy[index_ori][0]) 
     {
         Scalar color(rand() & 255, rand() & 255, rand() & 255);  
         //描绘字符的外轮廓
         drawContours(original,contours,index_ori,Scalar(255),1,8, hierarchy);  
         Rect rect = boundingRect(contours[index_ori]);//检测外轮廓
         //对外轮廓加加矩形框  
         rectangle(original, rect, Scalar(0,0,255), 3);  
    }
    //print contours info
    cout<<"The number of external contours:"<<contours.size()<<endl;
    imshow("Contours on original image",original);  
    waitKey(0);
     return 0;
}

二、程序运行效果图:

(1)源图像:

这里写图片描述
(2)灰度图像:
这里写图片描述
(3)二进制图像:
这里写图片描述
(4)轮廓在空白图像上显示:
这里写图片描述
(5)在原图像上画出图像的轮廓以及外接矩形:
这里写图片描述
至此,图像的轮廓检测以及外接矩形已经实现,欢迎高人指正。

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linda Fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值