使用Python和NumPy创建定向边界框(OBB)

5
我已经将这个示例翻译成了Python。
我的代码如下:
import numpy
a  = numpy.array([(3.7, 1.7), (4.1, 3.8), (4.7, 2.9), (5.2, 2.8), (6.0,4.0), (6.3, 3.6), (9.7, 6.3), (10.0, 4.9), (11.0, 3.6), (12.5, 6.4)])
ca = numpy.cov(a,y = None,rowvar = 0,bias = 1)
print ca
v, vect = numpy.linalg.eig(ca)
tvect = numpy.transpose(vect)
print tvect

变量ca在这个例子中等同于协方差矩阵,而tvect则等同于特征向量。

请问我需要做些什么来完成这个列表并建立边界框呢?

通常而言,这个列表对于三维点集也是完全相同的吗? 谢谢!


2
差不多 翻译了这个例子。为什么不先完成它,然后再看看它是否有效呢?(顺便说一句,OBB与面向对象编程无关) - mkrieger1
我不知道在最后一步需要做什么!如果我能完成的话,就不会问这个问题了。 - sevatster
这里有一个更好的参考资料,附有解释。http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf - user1121588
1个回答

12
他没有完全解释他如何得到中心点和最终的边界框,但我认为这应该可以解决问题:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

a  = np.array([(3.7, 1.7), (4.1, 3.8), (4.7, 2.9), (5.2, 2.8), (6.0,4.0), (6.3, 3.6), (9.7, 6.3), (10.0, 4.9), (11.0, 3.6), (12.5, 6.4)])
ca = np.cov(a,y = None,rowvar = 0,bias = 1)

v, vect = np.linalg.eig(ca)
tvect = np.transpose(vect)



fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111)
ax.scatter(a[:,0],a[:,1])

#use the inverse of the eigenvectors as a rotation matrix and
#rotate the points so they align with the x and y axes
ar = np.dot(a,np.linalg.inv(tvect))

# get the minimum and maximum x and y 
mina = np.min(ar,axis=0)
maxa = np.max(ar,axis=0)
diff = (maxa - mina)*0.5

# the center is just half way between the min and max xy
center = mina + diff

#get the 4 corners by subtracting and adding half the bounding boxes height and width to the center
corners = np.array([center+[-diff[0],-diff[1]],center+[diff[0],-diff[1]],center+[diff[0],diff[1]],center+[-diff[0],diff[1]],center+[-diff[0],-diff[1]]])

#use the the eigenvectors as a rotation matrix and
#rotate the corners and the centerback
corners = np.dot(corners,tvect)
center = np.dot(center,tvect)

ax.scatter([center[0]],[center[1]])    
ax.plot(corners[:,0],corners[:,1],'-')

plt.axis('equal')
plt.show()

在此输入图片描述


np.linalg.inv(tvect) 相当于 vect,因为旋转矩阵的逆矩阵是其转置矩阵。 - Eddmik
你需要将一个角落添加两次(中心+[-diff[0],-diff[1]])。 - Patricio Astudillo
我正在处理一个有趣的案例,其中a = np.array([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])。这个方法是否不能保证最小面积,而只是找到第一个解?奇怪的是,去掉最后一个元素后得到了“预期”的边界框。非常感谢任何想法! - fishmulch
更新:已经弄明白了,抱歉。 - fishmulch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接