python - 图像的轮廓轴

标签 python opencv image-processing contour x-ray

对于射线照相扫描,我已经能够获取轮廓。

我有兴趣找到中心轴。我怎么能在 python 中做到这一点?

enter image description here

这是我的轮廓代码:

import cv2


img = cv2.imread("A.png")


imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(img,60,200)

contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

hierarchy = hierarchy[0]


cv2.drawContours(img, contours, -1, (255,0,0), 3)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

最佳答案

我可能通过回答“给我工作的 Python 代码”类型的“问题”让这个世界变得更糟,但话又说回来,我自己需要时不时地使用 PCA 并且永远不记得正确的方法使用它,所以这可以作为一个小备忘录。

假设我们有一个单独的脚趾骨骼轮廓的黑白图像:

enter image description here

让我们用 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)

结果:

enter image description here

不同的骨头怎么样?很难看到线条,但仍然有效:

enter image description here

关于python - 图像的轮廓轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43863931/

相关文章:

python - 使用opencv dnn readNetFromModelOptimizer时发生错误(预期: 'inputShapeLimitation.size() == blobShape.size()')

c++ - 使用 CUDA 和 OpenCV 删除一个图像 channel

algorithm - 关于如何使用 OpenCV 或其他算法删除 png 中的小废弃像素的任何想法?

python - 函数返回一个向量,如何通过 NumPy 最小化

python - 类型错误 : object of type 'int' has no len() - Python/Pygame

python - Canny 运算符破坏图像边缘

android - 将图像转换为位图

android - 如何在 GPUImageView 中将一种效果应用到另一种效果之上?

python - 从 Python 调用 C 函数(无返回值)

python - 索引错误: list index out of range error when reversing a list