Creating a "white" image in numpy (2-D image) Creating a "white" image in numpy (2-D image) numpy numpy

Creating a "white" image in numpy (2-D image)


When displaying a 2D array using a colormap, matplotlib will first normalize the data such that it lies between 0 and 1.

Your white array is composed solely of 255's, when attempting to normalize an array of equal values, documentation states that they are all converted to 0 (see above link), resulting in a black rendering. To manually specify a range, use:

plt.imshow(img, cmap='gray', vmin=0, vmax=255)

You can also try setting the first pixel in your img_bw array to any value <255 and using your original method to show it, you should see an all white image with a black square in the corner.


As for why this "worked":

img = io.imread("https://www.colorcombos.com/images/colors/FFFFFF.png" , as_grey=True)plt.imshow(img*255, cmap = "gray")

There's a thin grey border around the image in that link, so after normalization, the grey border (darkest part of the image) is scaled to 0 (black) and the rest of the white interior stays white.


Using PIL to encode the array as an image is one way to go -

img_bw = np.ones([100,100], dtype=np.uint8)*255img = Image.fromarray(img_bw)img.show()

Output

enter image description here

For black, if you just change to img_bw = np.ones([100,100], dtype=np.uint8)*0 you get - enter image description here