图像的轮廓轴 [英] Contour Axis for Image

查看:264
本文介绍了图像的轮廓轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于放射线扫描,我已经能够获得轮廓。

For a radiographic scan, I have been able to acquire the contours.

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

I would be interested to find the center axis. How could I do it in python?

这是我的轮廓代码:

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()


推荐答案

我可能通过回答gimme the working Python code类型的问题让这个世界变得更糟糕,但是我自己也需要不时使用PCA并且永远不会记住使用它的正确方法,所以这可以作为一个小备忘录。

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:

让我们用PCA找到骨骼方向:

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 = []
for col in range(w):
    for row in range(h):
        if img[row, col] != 0:
            mat.append([col, row])
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)

结果:

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

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

使用Numpy可能有更好的方法为PCA创建输入矩阵,但这甚至不是必需的,因为已经有轮廓点可用。但TS的代码在我的机器上不起作用,因此我使用手工制作的BW图像作为快速解决方法。我给他留下了适当的比例和漂亮的绘画作为练习。

There's probably a better way to create the input matrix for PCA with Numpy, but that isn't even necessary because there are contour points available already. But the TS's code didn't work on my machine, so I used a handmade BW image as a quick workaround. I leave proper scaling and pretty drawing to him as an exercise.

这篇关于图像的轮廓轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆