返回图像的特定Numpy标签索引 [英] Returning specific numpy label indices for an image
问题描述
我想使用numpy的标签对图像进行细分,然后根据每个标签中找到的索引数删除那些符合我条件的索引.例如,如果这样创建的图像具有我要分割的区域,并使用scipy的label
:
I'd like to segment my image using numpy's label and then based on the number of indices found in each label remove those which satisfy my criteria. For example if an image with regions in it that I'd segmented were created like this and segmented using scipy's label
:
from numpy import ones, zeros
from numpy.random import random_integers
from scipy.ndimage import label
image = zeros((512, 512), dtype='int')
regionator = ones((11, 11), dtype='int')
xs = random_integers(5, 506, size=500)
ys = random_integers(5, 506, size=500)
for x, y in zip(xs, ys):
image[x-5:x+6, y-5:y+6] = regionator
labels, n_labels = label(image)
现在,我想检索每个区域的索引,该区域的大小大于121像素(或一个区域分割器大小).然后,我想获取这些索引并将它们设置为零,这样它们就不再是标记图像的一部分.完成这项任务的最有效方法是什么?
Now I'd like to retrieve the indices for each region which has a size greater than 121 pixels (or one regionator size). I'd then like to take those indices and set them to zero so they are no longer part of the labeled image. What is the most efficient way to accomplish this task?
本质上类似于MATLAB的 regionprops 或利用IDL的 reverse_indices 从其直方图函数中输出.
Essentially something similar to MATLAB's regionprops or utilizing IDL's reverse_indices output from its histogram function.
推荐答案
我将使用bincount并将结果阈值以创建查找表:
I would use bincount and threshold the result to make a lookup table:
import numpy as np
threshold = 121
size = np.bincount(labels.ravel())
keep_labels = size <= threshold
# Make sure the background is left as 0/False
keep_labels[0] = 0
filtered_labels = keep_labels[labels]
在上面的最后一个中,我用数组labels
索引了数组keep_labels
.这在numpy中称为高级索引,要求labels
是整数数组.然后,Numpy使用labels
的元素作为keep_labels
的索引,并生成与labels
形状相同的数组.
On the last above I index the array keep_labels
with the array labels
. This is called advanced indexing in numpy and it requires that labels
be an integer array. Numpy then uses the elements of labels
as indices to keep_labels
and produces an array the same shape as labels
.
这篇关于返回图像的特定Numpy标签索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!