Reputation: 11
I'm trying to find the pixel values of the corners of these triangles. I can use Harris corners and obtain a numpy array of all the x,y for the corners. I want these corner values to be stored in a 2D list called corners like [[x1,y1], [x2,y2], [x3,y3]]
.
Also, when I use Harris corners on a black triangle(code posted below), white background, the results are as such (array([121, 121, 122, 122, 123, 123, 124, 124, 359, 359, 359, 359, 359, 359, 360, 360, 360, 360], dtype=int64), array([240, 241, 240, 241, 240, 241, 240, 241, 121, 122, 123, 358, 359,360, 121, 122, 359, 360], dtype=int64))
. I need to create the 2D list of 3 corners from this list.
img = cv2.imread(filePath)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = numpy.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
x,y = numpy.nonzero(dst > 0.01 * dst.max())
Upvotes: 1
Views: 973
Reputation: 23002
With the current values that you have the easiest thing to do is apply k-means, which will cluster the data into k groups and give you the centers of those groups. You can check out the OpenCV k-means Python tutorial here and also check out the cv2.kmeans()
docs.
So starting with points in the form:
>>> X = np.array([121, 121, 122, 122, 123, 123, 124, 124, 359, 359, 359, 359, 359, 359, 360, 360, 360, 360], dtype=np.int64)
>>> Y = np.array([240, 241, 240, 241, 240, 241, 240, 241, 121, 122, 123, 358, 359, 360, 121, 122, 359, 360], dtype=np.int64)
We'll create a numpy array holding the points together as 32-bit floats for the input to cv2.kmeans()
:
>>> points = np.array([[x, y] for x, y in zip(X,Y)], dtype=np.float32)
The final thing is to run cv2.kmeans()
and grab the centers:
>>> criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
>>> centers = cv2.kmeans(points, 3, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)[2]
>>> centers
array([[ 122.5 , 240.5 ],
[ 359.3999939 , 359.20001221],
[ 359.3999939 , 121.80000305]], dtype=float32)
Of course, you can round to the nearest integer if you need to afterwards.
Upvotes: 1