2015-06-07 60 views
2

我对图像执行了均值偏移分割并获得了标签数组,其中每个点值对应于它所属的分段。根据另一个数组中的信息对NumPy数组进行操作

labels = [[0,0,0,0,1], 
      [2,2,1,1,1], 
      [0,0,2,2,1]] 

另一方面,我有相应的grayScale图像,并希望独立执行每个区域的操作。

img = [[100,110,105,100,84], 
     [ 40, 42, 81, 78,83], 
     [105,103, 45, 52,88]] 

比方说,我想每个区域的灰阶值的总和,如果是< 200,我想这些点设置为0(在这种情况下,在区域2中的所有点),如何我会用numpy做那个吗?我确定有比我已经开始的实现更好的方法,其中包括很多很多的循环和临时变量...

回答

2

查找到numpy.bincount和numpy.where,应该让你开始。例如:

import numpy as np 
labels = np.array([[0,0,0,0,1], 
        [2,2,1,1,1], 
        [0,0,2,2,1]]) 
img = np.array([[100,110,105,100,84], 
       [ 40, 42, 81, 78,83], 
       [105,103, 45, 52,88]]) 

# Sum the regions by label: 
sums = np.bincount(labels.ravel(), img.ravel()) 

# Create new image by applying threhold 
final = np.where(sums[labels] < 200, -1, img) 
print final 
# [[100 110 105 100 84] 
# [ -1 -1 81 78 83] 
# [105 103 -1 -1 88]] 
1

您正在寻找numpy函数where。这里就是你得到是如何开始的:

import numpy as np 

labels = [[0,0,0,0,1], 
       [2,2,1,1,1], 
       [0,0,2,2,1]] 

img = [[100,110,105,100,84], 
      [ 40, 42, 81, 78,83], 
      [105,103, 45, 52,88]] 

# to sum pixels with a label 0: 
px_sum = np.sum(img[np.where(labels == 0)]) 
+0

哇,我爱numpy:D这正是我所期待的,谢谢! – xShirase

相关问题