2017-02-22 30 views
2

的对象细胞计数的正确方法假设你有一个numpy.array形式的图像:Scikit形象:在图像

vals=numpy.array([[3,24,25,6,2],[8,7,6,3,2],[1,4,23,23,1],[45,4,6,7,8],[17,11,2,86,84]]) 

而且要计算多少个小区各对象的内部,给予(实施例)的阈值:

from scipy import ndimage 
from skimage.measure import regionprops 

blobs = numpy.where(vals>17, 1, 0) 
labels, no_objects = ndimage.label(blobs) 
props = regionprops(blobs) 

如果选中,这给出了超过阈值的4级不同的对象的图像:

In[1]: blobs 
Out[1]: 
array([[0, 1, 1, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 1, 1, 0], 
     [1, 0, 0, 0, 0], 
     [0, 0, 0, 1, 1]]) 

事实上:

In[2]: no_objects 
Out[2]: 4 

我要计算每个对象的细胞(或区域)的数量。预期的结果是与object ID: number of cells格式的词典:

size={0:2,1:2,2:1,3:2} 

我尝试:

size={} 
for label in props: 
    size[label]=props[label].area 

返回一个错误:

Traceback (most recent call last): 

    File "<ipython-input-76-e7744547aa17>", line 3, in <module> 
    size[label]=props[label].area 

TypeError: list indices must be integers, not _RegionProperties 

我明白我使用label不当,但目的是迭代对象。 如何做到这一点?

回答

1

regionprops会产生大量的比每个斑的只是该地区的更多信息。所以,如果你只是希望得到的斑点的像素数,作为替代,并集中表现,我们可以labels使用np.bincountndimage.label获得的,就像这样 -

np.bincount(labels.ravel())[1:] 

因此,对于给定的样本 -

In [53]: labeled_areas = np.bincount(labels.ravel())[1:] 

In [54]: labeled_areas 
Out[54]: array([2, 2, 1, 2]) 

要让这些结果在一本字典,一个额外的步骤将是 -

In [55]: dict(zip(range(no_objects), labeled_areas)) 
Out[55]: {0: 2, 1: 2, 2: 1, 3: 2} 
+1

我喜欢这个,谢谢。我的解决方案只是为了解决这个问题,但我们知道性能是关键。 – FaCoffee

1

一些测试和研究有时会有很长的路要走。

的问题都与blobs,因为它没有携带不同的标签,但只有0,1值和label,需要由一个迭代器遍历range(0,no_objects)所取代。

该解决方案似乎是工作:

import skimage.measure as measure 
import numpy 
from scipy import ndimage 
from skimage.measure import regionprops 

vals=numpy.array([[3,24,25,6,2],[8,7,6,3,2],[1,4,23,23,1],[45,4,6,7,8],[17,11,2,86,84]]) 

blobs = numpy.where(vals>17, 1, 0) 
labels, no_objects = ndimage.label(blobs) 

#blobs is not in an amicable type to be processed right now, so: 
labelled=ndimage.label(blobs) 
resh_labelled=labelled[0].reshape((vals.shape[0],vals.shape[1])) #labelled is a tuple: only the first element matters 

#here come the props 
props=measure.regionprops(resh_labelled) 

#here come the sought-after areas 
size={i:props[i].area for i in range (0, no_objects)} 

结果:

In[1]: size 
Out[1]: {0: 2, 1: 2, 2: 1, 3: 2} 

如果有人想以检查labels

In[2]: labels 
Out[2]: 
array([[0, 1, 1, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 2, 2, 0], 
     [3, 0, 0, 0, 0], 
     [0, 0, 0, 4, 4]]) 

如果有人想绘制发现的4个对象:

import matplotlib.pyplot as plt 
plt.set_cmap('OrRd') 
plt.imshow(labels,origin='upper') 

enter image description here

1

要回答的原稿伊纳勒问题:

  • 你必须regionprops适用于标签图像:props = regionprops(labels)

  • 然后,您可以构建字典使用:

    size = {r.label: r.area for r in props}

    这将产生

    {1: 2, 2: 2, 3: 1, 4: 2}