opencv 之对象提取

opencv 专栏收录该内容
24 篇文章 0 订阅

在这里插入图片描述

#include <QCoreApplication>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

//对象提取
int main()
{
   Mat src=imread("../image/11.png",IMREAD_GRAYSCALE);
    if(src.empty())
    {
        printf("could not load image ...");
        return ;
    }
    imshow("src",src);
    //binary image
    Mat binary,morhpImg;
    //二值化操作
    threshold(src,binary,0,255,THRESH_BINARY|THRESH_OTSU);
    //形态学操作 闭操作
    Mat kernel=getStructuringElement(MORPH_RECT,Size(5,5),Point(-1,-1));
    morphologyEx(binary,morhpImg,MORPH_CLOSE,kernel,Point(-1,-1));
    //形态学操作 开操作
    kernel=getStructuringElement(MORPH_RECT,Size(5,5),Point(-1,-1));
    morphologyEx(morhpImg,morhpImg,MORPH_OPEN,kernel,Point(-1,-1));
    imshow("output1",morhpImg);

    vector<vector<Point>> contours;
    vector<Vec4i> hireachy;
    //找轮廓
    findContours(morhpImg,contours,hireachy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
    Mat resultImg=Mat::zeros(src.size(),CV_8UC3);
    Point cc;
    for(int i=0;i<contours.size();++i)
    {
        //求面积
        double aera=contourArea(contours[i]);
        if(aera <200 ||aera>6000) continue;
        printf("aera:%2f\n",aera);
        //横纵比过滤
        Rect rec=boundingRect(contours[i]);
        float ratio=float(rec.width)/float(rec.height);      
          //thickness-1整个填充
           /* drawContours( InputOutputArray image, InputArrayOfArrays contours,
                                          int contourIdx, const Scalar& color,
                                          int thickness = 1, int lineType = LINE_8,
                                          InputArray hierarchy = noArray(),
                                          int maxLevel = INT_MAX, Point offset = Point() );
           */
             //绘制轮廓
              drawContours(resultImg,contours,i,Scalar(0,0,255),-1,8,Mat(),0,Point());
              printf("aera:%2f\n",aera);
              printf("aera:%2f\n",arcLength(contours[i],true));

              int x=rec.x+rec.width/2;
              int y=rec.y+rec.height/2;
              cc=Point(x,y);
              //画圆
              circle(resultImg,cc,2,Scalar(0,0,255),2,8,0);
    }
    imshow("output2",resultImg);
    Mat circleImg=src.clone();
    cvtColor(circleImg,circleImg,COLOR_GRAY2BGR);
    circle(circleImg,cc,2,Scalar(0,0,255),2,8,0);
    imshow("output3",circleImg);
    waitKey(0);
	retur 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值