OpenCV 计算面积、角度、距离
主要模块:
cv::Contours轮廓、cv::Moments矩、cv::minAreaRect最小外接矩形、点之间欧式距离、向量夹角。 全部基于 C++ OpenCV,给可直接复制核心代码 + 原理。
1. 两点之间距离(欧式距离)
两点 Point2f p1, p2 \(dist=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\)
cpp
#include <opencv2/opencv.hpp>
#include <cmath>
using namespace cv;
// 两点距离
float pointDistance(Point2f p1, Point2f p2)
{
float dx = p2.x - p1.x;
float dy = p2.y - p1.y;
return sqrt(dx*dx + dy*dy);
}
OpenCV 内置函数:
cpp
float d = norm(p2 - p1);
2. 轮廓面积 contourArea
单位:像素 ²,只对轮廓点集计算。
cpp
vector<vector<Point>> contours;
findContours(binaryImg, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for(auto& cnt : contours)
{
double area = contourArea(cnt);
if(area < 100) c

2187

被折叠的 条评论
为什么被折叠?



