OpenCV_Find Contours (提取图像轮廓)

#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));//自定义结构元素5x5
	cv::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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

惊鸿一博

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

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

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

打赏作者

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

抵扣说明:

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

余额充值