Search code examples
python-3.xnumpyscipyscikit-imagenumpy-ndarray

visualize the value distribution for a given numpy array


I have a matrix, e.g., generated as follows

x = np.random.randint(10,size=(20,20))

How to visualize the matrix with respect to the distribution of a given value, i.e., 6 In other words, how to show the matrix as an image, where the pixels with corresponding matrix entries being equivalent to 6 will be shown as white, while other pixels will be shown as black.


Solution

  • The simplest way to display the distribution of a given value through a black and white image is using a boolean array like x == 6. If you wish to improve visualization by replacing black and white with custom colors, NumPy's where will come in handy:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.random.randint(10, size=(20, 20))
    
    value = 6
    foreground = [255, 0, 0]  # red
    background = [0, 0, 255]  # blue
    
    bw = x == value
    rgb = np.where(bw[:, :, None], foreground, background)
    
    fig, ax = plt.subplots(1, 2)
    ax[0].imshow(bw, cmap='gray')
    ax[0].set_title('Black & white')
    ax[1].imshow(rgb)
    ax[1].set_title('RGB')
    plt.show(fig)
    

    output