OpenCV_Find Contours (提取图像轮廓)

来源:互联网 发布:淘宝直播端口 编辑:程序博客网 时间:2024/05/01 05:10
#include "stdafx.h"#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>#include <iostream>int main(){cv::Mat image = cv::imread("../../aTestImage/cow.jpg", 0);if (!image.data)  return 0;cv::Mat binary;cv::threshold(image, binary, 60, 255, CV_THRESH_BINARY_INV);//获取二值图像////方式1:////闭运算-闭洞(先膨胀再腐蚀)//cv::dilate(binary, binary, cv::Mat(), cv::Point(0, 0), 2);//cv::erode(binary, binary, cv::Mat(), cv::Point(0, 0), 2);////开运算-去小(先腐蚀再膨胀)//cv::erode(binary, binary, cv::Mat(), cv::Point(0, 0), 2);//cv::dilate(binary, binary, cv::Mat(), cv::Point(0, 0), 2);//方式2:cv::Mat element5(5, 5, CV_8U, cv::Scalar(255));//自定义结构元素5x5cv::morphologyEx(binary, binary, cv::MORPH_CLOSE, element5);//闭运算cv::morphologyEx(binary, binary, cv::MORPH_OPEN , element5);//开运算//cv::namedWindow("Closed_Opened");//cv::imshow("Closed_Opened", binary);std::vector <std::vector<cv::Point>>contours;//从经过开闭运算的二值图像中提取轮廓cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//获取所有external轮廓//画轮廓到白色背景图片上//cv::Mat result(image.size(), CV_8U, cv::Scalar(255));//定义8位纯白图片一张//cv::drawContours(result, contours, -1, cv::Scalar(0), 2);//cv::namedWindow("result");//cv::imshow("result", result);////移除过长或过短轮廓。。。。。//int cmin = 100;//int cmax = 1000;//std::vector<std::vector<cv::Point>>::const_iterator itc = contours.begin();//while (itc != contours.end())//{//if (itc->size()> cmax || itc->size()< cmin)//{//itc = contours.erase(itc);//}//else//{//++itc;//}//}//画轮廓到原始图像上cv::Mat image1 = cv::imread("../../aTestImage/cow.jpg");cv::drawContours(image1, contours, -1, cv::Scalar(255, 255, 255), 2);cv::namedWindow("result11");cv::imshow("result11", image1);cv::waitKey(0);return 0;}

0 0
原创粉丝点击