获取轮廓线上的点坐标

参考文献

http://blog.csdn.net/hw140701/article/details/54381252#


#include <iostream>   
#include <fstream>  
#include <opencv2/opencv.hpp>  
#include <math.h>  
using namespace cv;
using namespace std;
int main()
{
	//载入原始图,且必须以二值图模式载入  
	Mat M = imread("1.png", 0);
	imshow("原始图", M);

	//初始化结果图  
	Mat dstImage = Mat::zeros(M.rows, M.cols, CV_8UC3);
	int ElementShape = MORPH_RECT;

	Mat element = getStructuringElement(ElementShape, Size(2 * 2 + 1,
			2 * 2 + 1), Point(2, 2));
	
	morphologyEx(M, dstImage, MORPH_OPEN, element, Point(-1, -1), 4);
	
	
		imshow("【开运算】", dstImage);
	//定义轮廓和层次结构  
	vector<vector<Point>>contours;
	vector<Vec4i>hierarchy;
	findContours(dstImage, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE);
	//迭代器输出  
	/*for (vector<vector<Point>>::iterator it=contours.begin();it!=contours.end();++it)
	{
	for (vector<Point>::iterator inner_it=it->begin();inner_it!=it->end();++inner_it)
	{
	cout<<*inner_it<<endl;
	}
	}
	*/
	//下标输出  
	for (int i = 0; i<contours.size(); i++)
	{
		for (int j = 0; j<contours[i].size(); j++)
		{
			cout << contours[i][j].x << "   " << contours[i][j].y << endl;
			/*ofstream f;
			f.open("E:/坐标轮廓线.txt", ios::out | ios::app);
			f << contours[i][j].x << "  " << contours[i][j].y << endl;*/
		}
	}

	//遍历顶层轮廓,以随机颜色绘制出每个连接组件颜色  
	int index = 0;
	for (; index >= 0; index = hierarchy[index][0])
	{
		Scalar color(rand() % 255, rand() % 255, rand() % 255);
		drawContours(dstImage, contours, index, color, 1, 8, hierarchy);
	}

	imshow("轮廓图", dstImage);
	waitKey(5000); //等待5000ms后窗口自动关闭  
	getchar();
}

这篇博客解决了求取轮廓线上的点坐标,又使用了#include<math.h> 库,终于增加了新的知识。
获取了点坐标后,就可以用下面三种方式计算像素间的距离:
//计算欧氏距离的函数
float calcEuclideanDiatance(int x1, int y1, int x2, int y2)
{
return sqrt(float((x2 - x1)(x2 - x1) + (y2 - y1)(y2 - y1)));
}

//计算棋盘距离的函数 也叫做马氏距离
int calcChessboardDistance(int x1, int y1, int x2, int y2)
{
return cv::max(abs(x1 - x2), (y1 - y2));
}

//计算麦哈顿距离(街区距离)
int calcBlockDistance(int x1, int y1, int x2, int y2)
{
return abs(x1 - x2) + abs(y1 - y2);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值