I've almost translated into the Python this example
My listing is
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
Variable ca is the same as covariance matrix in the example and tvect is the same as eigenvectors in the example.
May you promt me what will I done to finish this listing and build a bounding box please?
In general is the exactly same listing works for 3D point sets? Thanks!
He does not fully explain how he gets the center and the final bounding box, but I think this should work:
%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()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With