【编程基础】计算三个顶点之间的夹角

前言

 

code

float calculateAngle(cv::Point pre, cv::Point cur, cv::Point next){
    cv::Point v1 = {pre.x-cur.x, pre.y-cur.y}; // ABC, BA
    cv::Point v2 = {next.x-cur.x, next.y-cur.y}; // ABC, BC
    double dotProduct = v1.x * v2.x + v1.y * v2.y;
    double normProduct = std::sqrt(v1.x * v1.x + v1.y * v1.y) * std::sqrt(v2.x * v2.x + v2.y * v2.y);
    float angleR = std::acos(dotProduct / normProduct);
    // Convert from radians to degrees
    float angleD =  angleR * 180.0 / CV_PI;
    return  angleD;   
}

float calculateAngleB(cv::Point pre, cv::Point cur, cv::Point next) {  
    cv::Point v1 = {cur.x - pre.x, cur.y - pre.y};  
    cv::Point v2 = {next.x - cur.x, next.y - cur.y}; // 修正了向量v2的计算  
    double dotProduct = v1.x * v2.x + v1.y * v2.y;  
    double normProduct = std::sqrt(v1.x * v1.x + v1.y * v1.y) * std::sqrt(v2.x * v2.x + v2.y * v2.y);  
    double angleRadians = std::acos(dotProduct / normProduct); // 使用double类型来保持精度  
    float angleDegrees = static_cast<float>(angleRadians * 180.0 / CV_PI); // 将弧度转换为度数并转换为float类型  
    return (180.0-angleDegrees);  
}

// 计算两点间距离的函数  
double distance(cv::Point p1, cv::Point p2) {  
    return std::sqrt(std::pow(p2.x - p1.x, 2) + std::pow(p2.y - p1.y, 2));  
} 

float calculateAngleC(cv::Point A, cv::Point B, cv::Point C) {  
    // 计算三角形的三边长度  
    double a = distance(B, C); // BC边  
    double b = distance(A, C); // AC边  
    double c = distance(A, B); // AB边  
    // 应用余弦定理计算cosB  
    double cosB = (a * a + c * c - b * b) / (2 * a * c);  
    // 注意:acos函数返回的是弧度值,需要转换为度数  
    // 转换公式为:度数 = 弧度 * 180 / π  
    float angleB_degrees = std::acos(cosB) * 180.0 / CV_PI; // M_PI是math.h中定义的π值  
    // 返回角B的度数  
    return angleB_degrees;  
}  
View Code

 

参考

1.

posted on 2024-12-09 16:37  鹅要长大  阅读(12)  评论(0编辑  收藏  举报

导航