python - 仅计算regionprops python中的特定属性

标签 python image-processing scikit-image connected-components

我正在使用 scikit-image 中提供的 measure.regionprops 方法来测量连接组件的属性。它计算一堆属性 ( Python-regionprops )。但是,我只需要每个连接组件的面积。有没有一种方法可以只计算一个属性并节省计算量?

最佳答案

使用 regionpropscache=False 似乎有更直接的方法来做同样的事情。我使用 skimage.segmentation.slicn_segments=10000 生成了标签。然后:

rps = regionprops(labels, cache=False)
[r.area for r in rps]

我对regionprops documentation的理解是设置 cache=False 意味着属性在被调用之前不会被计算。根据 Jupyter notebook 中的 %%time,运行上面的代码在 cache=False 时花费了 166ms,在 cache=True 时花费了 247ms,所以看起来去工作。

我尝试了与其他答案等效的方法,但发现速度要慢得多。

%%time
ard = np.empty(10000, dtype=int)
for i in range(10000):
   ard[i] = size(np.where(labels==0)[1])

这花了 34.3 秒。

这是一个完整的工作示例,使用 skimage 宇航员示例图像和切片分割生成的标签来比较这两种方法:

import numpy as np
import skimage
from skimage.segmentation import slic
from skimage.data import astronaut

img = astronaut()
# `+ 1` is added to avoid a region with the label of `0`
# zero is considered unlabeled so isn't counted by regionprops
# but would be counted by the other method.
segments = slic(img, n_segments=1000, compactness=10) + 1

# This is just to make it more like the original poster's 
# question.
labels, num = skimage.measure.label(segments, return_num=True)

使用 OP 建议的方法计算面积,并调整索引值以避免标签为零:

%%time
area = {}
for i in range(1,num + 1):
    area[i + 1] = np.size(np.where(labels==i)[1])

CPU 时间:用户 512 毫秒,系统:0 纳秒,总计:512 毫秒 挂墙时间:506 毫秒

使用 regionprops 的相同计算:

%%time
rps = skimage.measure.regionprops(labels, cache=False)
area2 = [r.area for r in rps]

CPU 时间:用户 16.6 毫秒,系统:0 纳秒,总计:16.6 毫秒 挂墙时间:16.2 毫秒

验证结果在元素方面是否相等:

np.equal(area.values(), area2).all()

正确

因此,只要考虑零标签和索引差异,两种方法都会给出相同的结果,但没有缓存的 regionprops 更快。

关于python - 仅计算regionprops python中的特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29216179/

相关文章:

python - 如何提高 matplotlib 中二维直方图的灵敏度?

python - 如何使用 Selenium 和 Python 2.7 单击表单中的按钮?

ios - OpenGL ES 2.0 损失图像质量

android - 检测皮肤并捕捉图像

python - 为什么 to_sql 不能与 pandas 中的 pyodbc 一起使用?

python - 如何将列表项从字符串转换为 int?

python - 值错误 : Images of type float must be between -1 and 1

python-3.x - 使用 python 应用 Wiener 滤波器去除噪声

opencv - 无法检测到图像上的等号

python - 图像处理——消除弧状拖影