OpenCV:查找和绘制轮廓

查找轮廓void cv::findContours()
绘制轮廓void cv::drawContours()

轮廓

轮廓可以简单地解释为连接具有相同颜色或强度的所有连续点(沿边界)的曲线。

详情:opencv学习(四十)之寻找图像轮廓findContours()

【OpenCV3】图像轮廓查找与绘制——cv::findContours()与cv::drawContours()详解

1.找到轮廓cv::findContours()

void cv::findContours(
		cv::InputOutputArray image, // 输入的8位单通道“二值”图像
		cv::OutputArrayOfArrays contours, // 包含points的vectors的vector
		cv::OutputArray hierarchy, // (可选) 拓扑信息
		int mode, // 轮廓检索模式
		int method, // 近似方法
		cv::Point offset = cv::Point() // (可选) 所有点的偏移
);


void cv::findContours(
		cv::InputOutputArray image, // 输入的8位单通道“二值”图像
		cv::OutputArrayOfArrays contours, // 包含points的vectors的vector
		int mode, // 轮廓检索模式
		int method, // 近似方法
		cv::Point offset = cv::Point() //  (可选) 所有点的偏移
);

2.绘制轮廓cv::drawContours()

void cv::drawContours(
		cv::InputOutputArray image, // 用于绘制的输入图像
		cv::InputArrayOfArrays contours, // 点的vectors的vector
		int contourIdx, // 需要绘制的轮廓的指数 (-1 表示 "all")
		const cv::Scalar& color, // 轮廓的颜色
		int thickness = 1, // 轮廓线的宽度
		int lineType = 8, //  轮廓线的邻域模式('4'邻域 或 '8'邻域)
		cv::InputArray hierarchy = noArray(), // 可选 (从 findContours得到)
		int maxLevel = INT_MAX, // 轮廓中的最大下降
		cv::Point offset = cv::Point() // (可选) 所有点的偏移
	)

 代码

#include<opencv2/opencv.hpp>
#include<iostream>
#include<imgproc.hpp>
using namespace cv;
using namespace std;

int main(int argc, char** argv) {
	Mat image = imread("C:/Users/YY/Pictures/Saved Pictures/1.jpg");
	Mat dst1, dst2;

	vector<vector<Point>>contours;
	vector<Vec4i>hierarchy;

	imshow("原图", image);
	cvtColor(image, dst1,COLOR_BGR2GRAY);
	imshow("灰度", dst1);

	threshold(dst1, dst1, 140, 255, THRESH_BINARY);
	//Canny(dst1, dst1, 10, 150);
	imshow("二值", dst1);
    //查找轮廓
	findContours(dst1, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
	dst1 = Scalar(0, 0, 0);

	drawContours(dst1, contours, -1, (255, 255, 255), 1);
	imshow("轮廓1", dst1);

	dst1 = Mat::zeros(image.size(), CV_8UC3);
	for (int i = 0; i < hierarchy.size(); i++) {
		Scalar color = Scalar(rand() % 255, rand() % 255, rand() % 255);
		drawContours(dst1, contours, i, color, FILLED, 8, hierarchy);
	}
	imshow("轮廓2", dst1);

	waitKey(0);
	destroyAllWindows();
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值