赞
踩
实现多边形 IOU 计算
#include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; struct Point { double x, y; Point(double _x = 0, double _y = 0) : x(_x), y(_y) {} }; typedef vector<Point> Polygon; double cross(const Point& a, const Point& b) { return a.x * b.y - a.y * b.x; } double area(const Polygon& p) { double a = 0; for (int i = 0; i < p.size(); i++) { int j = (i + 1) % p.size(); a += cross(p[i], p[j]); } return a / 2; } Polygon clip(const Polygon& p, const Point& a, const Point& b) { Polygon q; for (int i = 0; i < p.size(); i++) { int j = (i + 1) % p.size(); if (cross(b - a, p[i] - a) >= 0) q.push_back(p[i]); if (cross(b - a, p[i] - a) * cross(b - a, p[j] - a) < 0) { q.push_back(Point((cross(b - a, p[j] - a) * p[i].x - cross(b - a, p[i] - a) * p[j].x) / (cross(b - a, p[j] - a) - cross(b - a, p[i] - a)), (cross(b - a, p[j] - a) * p[i].y - cross(b - a, p[i] - a) * p[j].y) / (cross(b - a, p[j] - a) - cross(b - a, p[i] - a)))); } } return q; } Polygon intersection(const Polygon& p, const Polygon& q) { Polygon r = q; for (int i = 0; i < p.size(); i++) { int j = (i + 1) % p.size(); r = clip(r, p[j], p[i]); } return r; } Polygon join(const Polygon& p, const Polygon& q) { int pi = 0, qi = 0; Polygon r; while (pi < p.size() || qi < q.size()) { if (pi == p.size()) r.push_back(q[qi++]); else if (qi == q.size()) r.push_back(p[pi++]); else if (p[pi].y < q[qi].y) r.push_back(p[pi++]); else if (p[pi].y > q[qi].y) r.push_back(q[qi++]); else if (p[pi].x < q[qi].x) r.push_back(p[pi++]); else r.push_back(q[qi++]); } return r; } double iou(const Polygon& p, const Polygon& q) { Polygon r = intersection(p, q); double inter = area(r); double uni = area(join(p, q)); return inter / uni; } int main() { // test Polygon p; p.push_back(Point(0, 0)); p.push_back(Point(1, 0)); p.push_back(Point(1, 1)); p.push_back(Point(0, 1)); Polygon q; q.push_back(Point(0.5, 0.5)); q.push_back(Point(1.5, 0.5)); q.push_back(Point(1.5, 1.5)); q.push_back(Point(0.5, 1.5)); cout << iou(p, q) << endl; // should output 0.25 return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。