2

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@user3483203 Thank you for your remark. I've edited my answer to make it more versatile.
0

I think you want this:

from PIL import Image
import numpy as np

# Initialise data
x = np.random.randint(10,size=(20,20),dtype=np.uint8)

# Make all pixels with value 6 into white and all else black
x[x==6]   = 255
x[x!=255] = 0

# Make PIL Image from Numpy array
pi = Image.fromarray(x) 

# Display image
pi.show()

# Save PIL Image
pi.save('result.png')

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.