假设你得到了四个任意顺序的坐标,可以通过我编的程序获得该矩形的长宽,角度和中心点
import cv2
import math
class Point(object): # 坐标类
def __init__(self, xParam=0.0, yParam=0.0):
self.x = xParam
self.y = yParam
def distance(self, pt):
xDiff = self.x - pt.x
yDiff = self.y - pt.y
return math.sqrt(xDiff ** 2 + yDiff ** 2)
def show(self):
print("(%.2f, %.2f)" % (self.x, self.y))
def substract(self, pt): # 减法生成向量
newPt = Point()
xNew = self.x - pt.x
yNew = self.y - pt.y
return Point(xNew, yNew)
def add(self, pt): # 加法生成中心点
newPt = Point()
xNew = (self.x + pt.x) / 2
yNew = (self.y + pt.y) / 2
return Point(xNew, yNew)
# 求取两个向量间的余弦值
def cosVector(p1, p2):
result1 = p1.x * p2.x + p1.y * p2.y
result2 = p1.x ** 2 + p1.y ** 2
result3 = p2.x ** 2 + p2.y ** 2
return result1 / ((result2 * result3) ** 0.5)
# 有向矩形的四个顶点输入顺序任意时,返回旋转角度,w,h
def points_to_grasps(p, num=4, is_pos=True): # 默认矩形框的w大于h
res = []
p = sorted(p, key=lambda Points: Points.x)
d12 = p[0].distance(p[1])
d13 = p[0].distance(p[2])
center_O = p[0].add(p[3])
vector_OB = Point(1, 0)
w = min(d12, d13)
h = max(d12, d13)
if d12 > d13:
point_A = p[1].add(p[3])
else:
if p[1].y < p[2].y:
point_A = p[2].add(p[3])
else:
point_A = p[0].add(p[1])
vector_OA = point_A.substract(center_O)
if is_pos:
cos_AOB = cosVector(vector_OA, vector_OB)
box_class = cos_to_class(cos_AOB)
else:
box_class = 0
res.append(str(center_O.x))
res.append(str(center_O.y))
res.append(str(w))
res.append(str(h))
res.append(str(box_class))
return res
转载请附上链接