Opencv C++算子(三)轮廓查找findContours

135次阅读
没有评论

共计 1276 个字符,预计需要花费 4 分钟才能阅读完成。

调用opencv接口二值化后进行轮廓查找,然后使用line绘制出来边缘

#include <iostream>
#include <vector>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <omp.h>
using namespace std;
using namespace cv;

int main()
{
  setUseOptimized(true);
  Mat img = imread("F:/1.jpg");
  Mat copyImg,grayImg, binImg;
  cvtColor(img, grayImg, COLOR_BGR2GRAY);
  //提取二值化图像中的轮廓数据
  vector<vector<Point> > contour_vec;
  vector<Vec4i> hierarchy;
  img.copyTo(copyImg);
  int s = cv::getTickCount();
  //二值化
  threshold(grayImg, binImg, 100, 255, THRESH_BINARY_INV);
  //bitwise_not(binImg, binImg);
  //轮廓查找
  findContours(binImg, contour_vec, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE);

  //cout << "contours number: " << contour_vec.size() << endl;

  // 以前常用的for循环绘制轮廓
    /*Mat blkImg(binImg.size(), CV_8UC1, Scalar(0));

  for(int i = 0; i < contour_vec.size(); i++)
  {
    drawContours(blkImg, contour_vec, i, Scalar(255), -1);
  }   */

  //绘制单通道轮廓图像,背景为白色,轮廓线条用黑色
#pragma omp parallel for
  for (int i = 0; i < contour_vec.size(); i++)
  {
    //绘制轮廓的最小外结矩形
    RotatedRect rect = minAreaRect(contour_vec[i]);
    Point2f P[4];
    rect.points(P);
    for (int j = 0; j <= 3; j++)
    {
      line(copyImg, P[j], P[(j + 1) % 4], Scalar(255), 1);
    }
  }
  int e = cv::getTickCount();
  std::cout << "BlobDetect cost time: " << static_cast<double>(e - s) / cv::getTickFrequency() * 1000 << "ms" << std::endl;
  contour_vec.clear();
  hierarchy.clear();


  imshow("blkImg", copyImg);
  waitKey(0);


  return 0;

}

 

正文完
 
admin
版权声明:本站原创文章,由 admin 2022-06-03发表,共计1276字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码