在Python中使用regionprops

时间:2018-07-09 16:06:35

标签: python matlab image-processing scikit-image

我正在尝试分析灰度TIFF堆栈,其中给定的帧看起来像this。我将其过滤(使用高斯模糊),然后将其二值化(使用Otsu的阈值方法)。

MATLAB代码,效果很好:

image_conncomp = bwconncomp(image_binary); # entire stack is held in image_binary

for i=1:image_conncomp.NumObjects
    object_size = length(image_conncomp.PixelIdxList{i});
end

示例图像中的每个白点均被拾取,其体积(以像素为单位)由object_size精确给出。

Python代码:

from skimage import measure

labels = measure.label(image_binary, background=1) # same image_binary as above
propsa = measure.regionprops(labels)

for label in propsa:
    object_size = len(label.coords)

Python代码似乎运行得很好……除了大多数检测到的对象的object_size为1-200,然后一对夫妇的大小为几千个像素。

这些功能有何不同之处?我很乐意尝试使用Python的另一种方法来计算对象的大小,但是我很难找到另一种方法。如果我可以找到Matlab的bwconncomp函数的很好的替代品,那么拥有此代码的Python版本将是很棒的。

enter image description here

2 个答案:

答案 0 :(得分:3)

像这样吗?

from skimage.io import imread, imshow
from skimage.filters import gaussian, threshold_otsu
from skimage import measure
import matplotlib.pyplot as plt

original = imread('https://i.stack.imgur.com/nkQpj.png')
blurred = gaussian(original, sigma=.8)
binary = blurred > threshold_otsu(blurred)
labels = measure.label(binary)

plots = {'Original': original, 'Blurred': blurred, 
         'Binary': binary, 'Labels': labels}
fig, ax = plt.subplots(1, len(plots))
for n, (title, img) in enumerate(plots.items()):
    cmap = plt.cm.gnuplot if n == len(plots) - 1 else plt.cm.gray
    ax[n].imshow(img, cmap=cmap)
    ax[n].axis('off')
    ax[n].set_title(title)
plt.show(fig)

props = measure.regionprops(labels)
for prop in props:
    print('Label: {} >> Object size: {}'.format(prop.label, prop.area))

输出:

Plots

Label: 1 >> Object size: 37
Label: 2 >> Object size: 66
Label: 3 >> Object size: 1

答案 1 :(得分:0)

我们可以通过首先在阈值二进制图像上应用string retval = replacements .Aggregate(param, (str, x) => x.regex.Replace(str, x.replacement)); 的形态学闭合,然后使用scipy.ndimage函数将二进制图像中的连接区域合并来进行相同的操作,如下所示(但是这些区域有所不同,并且取决于形态内核的大小):

label()

获得以下输出:

enter image description here