首页 > 代码库 > 椭圆轮廓识别

椭圆轮廓识别

首先,从图像中检测出轮廓,然后再从轮廓中检索出椭圆轮廓。参考代码如下所示:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main(int argc, char *argv[]){
  cv::Mat src_img = cv::imread("test.jpg", 1);
  if(src_img.empty()) return -1; 

  cv::Mat gray_img, bin_img;
  cv::cvtColor(src_img, gray_img, CV_BGR2GRAY);

  std::vector<std::vector<cv::Point> > contours;

  cv::threshold(gray_img, bin_img, 0, 255, cv::THRESH_BINARY|cv::THRESH_OTSU);// 图像的二值化  
  cv::findContours(bin_img, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);// 轮廓检测

  for(int i = 0; i < contours.size(); ++i) {
    size_t count = contours[i].size();
    if(count < 100 || count > 1000) continue; // (过大或过小)排除轮廓

    cv::Mat pointsf;
    cv::Mat(contours[i]).convertTo(pointsf, CV_32F);
    
    cv::RotatedRect box = cv::fitEllipse(pointsf);// 椭圆形匹配    
    cv::ellipse(src_img, box, cv::Scalar(0,0,255), 2, CV_AA);// 绘制出椭圆
  }

  cv::namedWindow("fit ellipse", CV_WINDOW_AUTOSIZE|CV_WINDOW_FREERATIO);
  cv::namedWindow("bin image", CV_WINDOW_AUTOSIZE|CV_WINDOW_FREERATIO);
  cv::imshow("fit ellipse", src_img);
  cv::imshow("bin image", bin_img);
  cv::waitKey(0);
}


关于Image Engineering& Computer Vision更多讨论与交流,敬请关注本博客和新浪微博songzi_tea.