How to Correctly mask 3D Array with numpy

后端 未结 2 1263
野的像风
野的像风 2021-01-02 23:36

I\'m trying to mask a 3D array (RGB image) with numpy.

However, my current approach is reshaping the masked array (output below). I have tried to follow the approach

相关标签:
2条回答
  • 2021-01-02 23:57

    After finding the following post on loss of dimensions HERE, I have found a solution using numpy.where:

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

    This appears to work well.

    0 讨论(0)
  • 2021-01-02 23:59

    NumPy broadcasting allows you to use a mask with a different shape than the image. E.g.,

    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()
    

    0 讨论(0)
提交回复
热议问题