【问题标题】:How to Correctly mask 3D Array with numpy如何使用 numpy 正确屏蔽 3D 数组
【发布时间】:2019-06-19 09:08:20
【问题描述】:

我正在尝试用 numpy 屏蔽 3D 数组(RGB 图像)。

但是,我目前的方法是重塑掩码数组(输出如下)。 我尝试遵循 SciKit-Image 速成课程中描述的方法。 Crash Course

我查看了 Stackoverflow 并提出了类似的问题,但没有接受答案 (similar question here)

完成这样的屏蔽的最佳方法是什么?

这是我的尝试:

# create some random numbers to fill array
tmp = np.random.random((10, 10))

# create a 3D array to be masked
a = np.dstack((tmp, tmp, tmp))

# create a boolean mask of zeros
mask = np.zeros_like(a, bool)

# set a few values in the mask to true
mask[1:5,0,0] = 1
mask[1:5,0,1] = 1

# Try to mask the original array
masked_array = a[:,:,:][mask == 1]

# Check that masked array is still 3D for plotting with imshow
print(a.shape)
(10, 10, 3)

print(mask.shape)
(10, 10, 3)

print(masked_array.shape)
(8,)

# plot original array and masked array, for comparison
plt.imshow(a)
plt.imshow(masked_array)

plt.show()

【问题讨论】:

  • 您是在尝试从图像中选择值,还是使用遮罩将图像的某些部分设置为零?您希望蒙版是 2D 的,并应用于彩色图像,还是 3D——蒙版中的一个值对应图像中的每个值?
  • 我正在尝试选择图像的一部分 - 在这种情况下这是一个特征提取问题。因为我正在处理三通道图像,所以我假设我需要一个 3D 蒙版。但是,2D 蒙版更合适,因为应该在所有三个通道上屏蔽掉相同的像素

标签: python numpy scikit-image


【解决方案1】:

NumPy 广播允许您使用形状与图像不同的蒙版。例如,

import numpy as np
import matplotlib.pyplot as plt

# Construct a random 50x50 RGB image    
image = np.random.random((50, 50, 3))

# Construct mask according to some condition;
# in this case, select all pixels with a red value > 0.3
mask = image[..., 0] > 0.3

# Set all masked pixels to zero
masked = image.copy()
masked[mask] = 0

# Display original and masked images side-by-side
f, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(image)
ax1.imshow(masked)
plt.show()

【讨论】:

    【解决方案2】:

    在找到以下关于尺寸丢失HERE 的帖子后,我找到了使用 numpy.where 的解决方案:

    masked_array = np.where(mask==1, a , 0)

    这似乎运作良好。

    【讨论】:

      猜你喜欢
      • 2016-11-06
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多