Contour Axis for Image

无人久伴 提交于 2019-12-03 09:12:01

I am probably making this world a slightly worse place by answering a "gimme the working Python code" type of "question", but then again, I myself need to use PCA from time to time and can never remember the correct way of using it, so this may serve as a little memo.

Let's say we have a black and white image of a separate toe bone contour:

Let's find the bone direction with PCA:

import cv2
import numpy as np

#loading our BW image
img = cv2.imread("test_images/toe.bmp", 0)
h, w = img.shape

#From a matrix of pixels to a matrix of coordinates of non-black points.
#(note: mind the col/row order, pixels are accessed as [row, col]
#but when we draw, it's (x, y), so have to swap here or there)
mat = np.argwhere(img != 0)
mat[:, [0, 1]] = mat[:, [1, 0]]
mat = np.array(mat).astype(np.float32) #have to convert type for PCA

#mean (e. g. the geometrical center) 
#and eigenvectors (e. g. directions of principal components)
m, e = cv2.PCACompute(mat, mean = np.array([]))

#now to draw: let's scale our primary axis by 100, 
#and the secondary by 50
center = tuple(m[0])
endpoint1 = tuple(m[0] + e[0]*100)
endpoint2 = tuple(m[0] + e[1]*50)

cv2.circle(img, center, 5, 255)
cv2.line(img, center, endpoint1, 255)
cv2.line(img, center, endpoint2, 255)
cv2.imwrite("out.bmp", img)

The result:

How about a different bone? Hard to see the lines, but still works:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!