【32】C++实战篇—— m行n列的坐标点,求每行相邻点X差值dX,每列相邻点y差值dY,并以矩阵形式左端对齐

文章目录

  • [1 代码实现](#1 代码实现)
  • [2 示例验证](#2 示例验证)

m行n列的坐标点,求每行相邻点X差值dX,每列相邻点y差值dY,并以矩阵形式左端对齐

例如:
vector< cv::Point2f>Center中存储了3行3列的9个点,现在求每行相邻点X差值,那么每行有3-1个差值,一共有3行,就以32的形式输出;每列相邻点y差值,那么每列有3-1个差值,一共有3列,就以23的形式输出;

1 代码实现

cpp 复制代码
//输出3*3点阵坐标的行距、列距
int PutRowandColSpace(vector< cv::Point2f> Center)
{
	// 确保 points 包含了9个点
	if (Center.size() != 9) {
		std::cerr << "Error: The number of points should be 9." << std::endl;
		return -1; // 或者执行错误处理
	}

	// 计算每行相邻点的X差值并输出
	cout << "每行相邻点的X差值:" << endl;
	for (int i = 0; i < 3; ++i) {
		for (int j = 0; j < 2; ++j) {
			float dx = Center[i * 3 + j + 1].x - Center[i * 3 + j].x;
			cout << setw(5) << dx;
		}
		cout << endl;
	}

	// 计算每列相邻点的Y差值并输出
	cout << "每列相邻点的Y差值:" << endl;
	for (int i = 0; i < 2; ++i) {
		for (int j = 0; j < 3; ++j) {
			float dy = Center[(i + 1) * 3 + j].y - Center[i * 3 + j].y;
			cout << setw(5) << dy;
		}
		cout << endl;
	}

	return 0;
}

对于cv::Point2f Center[9]此方法同样适用,只是改一下入口参数即可

cpp 复制代码
////输出3*3点阵坐标的行距、列距
int PutRowandColSpace2(cv::Point2f Center[9])
{
	// 计算每行相邻点的X差值并输出
	cout << "每行相邻点的X差值:" << endl;
	for (int i = 0; i < 3; ++i) {
		for (int j = 0; j < 2; ++j) {
			float dx = Center[i * 3 + j + 1].x - Center[i * 3 + j].x;
			cout << setw(10) << dx;
		}
		cout << endl;
	}

	// 计算每列相邻点的Y差值并输出
	cout << "每列相邻点的Y差值:" << endl;
	for (int i = 0; i < 2; ++i) {
		for (int j = 0; j < 3; ++j) {
			float dy = Center[(i + 1) * 3 + j].y - Center[i * 3 + j].y;
			cout << setw(10) << dy;
		}
		cout << endl;
	}

	return 0;
}

2 示例验证

如图,在图片中找到9个点圆点坐标,现在需要检查9个圆心每行相邻点间距,和每列相邻点间距是否是否一致;

已求得9个圆心

cpp 复制代码
[863.396, 626.316]      [1484.38, 628.124]      [2108.53, 639.256]
[861.457, 751.556]      [1482.73, 756.879]      [2107.33, 766.905]
[861.085, 881.949]      [1481.89, 889.102]      [2104.66, 897.348]  

3*3点阵行距、列距:

cpp 复制代码
每行相邻点的X差值:
   620.984   624.151
   621.274   624.599
   620.803   622.774

每列相邻点的Y差值:
  125.241   128.755   127.649
  130.393   132.223   130.443