6

我有很多骷髅相似图片:我怎样才能找到与Python库的骨架图像中的周期?

enter image description here enter image description here

我如何可以检测一个周期,在骨架的循环? 有没有“特殊”的功能,或者我应该把它作为一个图来实现?

如果只有图形选项,那么Python图形库NetworkX可以帮助我吗?

+0

用python字典实现一个简单的图很容易。这里是[python文档的例子](http://www.python.org/doc/essays/graphs/)。尽管我从来没有使用过NetworkX,但看起来似乎过分了。关于将图像转换为图形,我不知道一个简单的方法来做到这一点,虽然它似乎是一个有趣的问题。我使用[opencv](http://opencv.org/),它提供了许多用于处理图像的功能。你可能会发现一些有用的部分。 – KobeJohn 2013-04-10 00:57:49

回答

3

您可以利用骨架的拓扑结构。一个循环将没有漏洞,所以我们可以使用scipy.ndimage找到任何漏洞并进行比较。这不是最快的方法,但编码非常简单。

import scipy.misc, scipy.ndimage 

# Read the image 
img = scipy.misc.imread("Skel.png") 

# Retain only the skeleton 
img[img!=255] = 0 
img = img.astype(bool) 

# Fill the holes 
img2 = scipy.ndimage.binary_fill_holes(img) 

# Compare the two, an image without cycles will have no holes 
print "Cycles in image: ", ~(img == img2).all() 

# As a test break the cycles 
img3 = img.copy() 
img3[0:200, 0:200] = 0 
img4 = scipy.ndimage.binary_fill_holes(img3) 

# Compare the two, an image without cycles will have no holes 
print "Cycles in image: ", ~(img3 == img4).all() 

我以您的“B”图片为例。前两张图像是原始图像和填充版本,用于检测周期。在第二个版本中,我打破了这个循环,没有任何东西被填充,因此这两个图像是相同的。

enter image description here

3

将您的骨架图像转换为图形表示并不重要,我也不知道有任何工具可以为您做。

在位图中做到这一点的一种方法是使用flood fill,就像photoshop中的油漆桶。如果您开始对图像进行泛洪填充,则如果没有循环,整个背景将被填充。如果填充没有得到整个图像,那么你已经找到了一个循环。可靠地查找所有循环可能需要多次填充。

这很可能执行起来非常慢,但可能比将跟踪框架跟踪到图形数据结构的技术快得多。

+1

我认为这是一个很好的解决方案。我计算像素的骨架数量和图像的像素总数,并计算差异,如果填充返回相同数量的像素,则不存在循环,如果返回更少,则存在循环。 – improc 2013-04-10 15:38:31

+0

是的,基本上你需要标记骨架的补充。这将返回由骨架循环切出的连接组件。如果组件的数量大于1,则表示N有N-1个循环。这也可以被看作是使骨架变薄的一种形式。 – beedot 2013-11-11 01:56:05

4

首先,让我们来构建字母B的图像与PIL:

import Image, ImageDraw, ImageFont 
image = Image.new("RGBA", (600,150), (255,255,255)) 
draw = ImageDraw.Draw(image) 
fontsize = 150 
font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf", fontsize) 
txt = 'B' 
draw.text((30, 5), txt, (0,0,0), font=font) 
img = image.resize((188,45), Image.ANTIALIAS) 
print type(img) 
plt.imshow(img) 

你会发现一个更好的方式来做到这一点,特别是与路径字体。 Ii会更好地加载图像,而不是生成它。无论如何,我们现在有一些关于工作: Upper B

现在,真正的部分:

import mahotas as mh 
img = np.array(img) 
im = img[:,0:50,0] 
im = im < 128 
skel = mh.thin(im) 
noholes = mh.morph.close_holes(skel) 
plt.subplot(311) 
plt.imshow(im) 
plt.subplot(312) 
plt.imshow(skel) 
plt.subplot(313) 
cskel = np.logical_not(skel) 
choles = np.logical_not(noholes) 
holes = np.logical_and(cskel,noholes) 
lab, n = mh.label(holes) 
print 'B has %s holes'% str(n) 
plt.imshow(lab) 

Holes labelling ,我们在控制台(IPython中): B有2个孔