python - 基于另一个数组中的信息对 NumPy 数组进行操作

标签 python arrays numpy

我对图像执行了均值平移分割并获得了标签数组,其中每个点值对应于它所属的片段。

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]]

比方说,我想要每个区域的灰度值之和,如果它<200,我想将这些点设置为0(在这种情况下,区域2中的所有点),我该怎么做与numpy?我确信有比我已经开始的实现更好的方法,其中包括很多很多 for 循环和临时变量...

最佳答案

查看 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]]

关于python - 基于另一个数组中的信息对 NumPy 数组进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30695248/

相关文章:

python - FlaskForm 验证码 : checking if a user already exists or not

python - DataReader 谷歌财务日期不工作

从这个列表中提取字符串的pythonic方法

javascript - 映射对象返回 "function map() { [native code] } ".. 为什么

python - 将多个 numpy 数组保存到一个 csv

python - 按 pandas 中的排名求和值

python - cx_Freeze python 3.4 无法安装 (Windows 10)

javascript - 如何直接追加Json对象?

php - Array PHP,检查是否存在多个元素到另一个数组

python - 使用 numpy 获取数组列表中相交元素的计数(避免循环)