import numpy as np
from shapely.geometry import Polygon
defintersection(g, p):# 取g,p中的幾何體信息組成多邊形
g = Polygon(g[:8].reshape((4,2)))
p = Polygon(p[:8].reshape((4,2)))# 判斷g,p是否爲有效的多邊形幾何體ifnot g.is_valid ornot p.is_valid:return0# 取兩個幾何體的交集和並集
inter = Polygon(g).intersection(Polygon(p)).area
union = g.area + p.area - inter
if union ==0:return0else:return inter / union
defweighted_merge(g, p):# 取g,p兩個幾何體的加權(權重根據對應的檢測得分計算得到)
g[:8]=(g[8]* g[:8]+ p[8]* p[:8])/(g[8]+ p[8])# 合併後的幾何體的得分爲兩個幾何體得分的總和
g[8]=(g[8]+ p[8])return g
defstandard_nms(S, thres):# 標準NMS
order = np.argsort(S[:,8])[::-1]
keep =[]while order.size >0:
i = order[0]
keep.append(i)
ovr = np.array([intersection(S[i], S[t])for t in order[1:]])
inds = np.where(ovr <= thres)[0]
order = order[inds +1]return S[keep]defnms_locality(polys, thres=0.3):'''
locality aware nms of EAST
:param polys: a N*9 numpy array. first 8 coordinates, then prob
:return: boxes after nms
'''
S =[]# 合併後的幾何體集合
p =None# 合併後的幾何體for g in polys:if p isnotNoneand intersection(g, p)> thres:# 若兩個幾何體的相交面積大於指定的閾值,則進行合併
p = weighted_merge(g, p)else:# 反之,則保留當前的幾何體if p isnotNone:
S.append(p)
p = g
if p isnotNone:
S.append(p)iflen(S)==0:return np.array([])return standard_nms(np.array(S), thres)