任意順序的四個點獲取矩形的中心點,長寬和角度
阿新 • • 發佈:2021-01-14
技術標籤:python
假設你得到了四個任意順序的座標,可以通過我編的程式獲得該矩形的長寬,角度和中心點
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
轉載請附上鍊接