1st case
#Import all libraries we will use
import numpy as np
#let's create a 10 x 10 matrix with all pixels in black color
img = np.zeros((10, 10), dtype= np.int8)
plt.imshow(img)
print(img)
Output:
Question 1: If a 10 by 10 array is initialized by zeros, why it is giving me a purple color image? Won't it suppose to give me a solid black color image?
I also read some code using 3rd value like np.zeros((10,10,1), dtype= np.int8)
. In the above code, what will be the default third value in shape? And I know the 3rd value represents the number of channels So, if it is true, then the purple image from the above output has how many channels?
2nd case
#Import all libraries we will use
import numpy as np
#let's create a 2 x 2 matrix with all pixels in black color
img = np.zeros((2,2,1), dtype= np.int8)
plt.imshow(img)
print(img)
Output:
Question 2:
From the output, we see that we are getting another dimension of the img
array using the 3rd value from shape. That means when we are not giving the 3rd value in shape, we get a 2 by 2 matrix or array. But, don't know how many channels in the 2 by 2 matrix case or in the 1st case of my code in this question. Please make my confusion clear here. And as I gave channel = 1 in my 2nd case, that means it represents the greyscale image, but, still, it gives me a purple color image. What am I missing here?
3rd case
#Import all libraries we will use
import numpy as np
#let's create a 2 x 2 matrix with all pixels in black color
img = np.zeros((2,2,3), dtype= np.int8)
plt.imshow(img)
print(img)
Output:
Question 3: From this output, What I understood is i am generating 2 by 2 size image, where in each pixel from total 4 pixels, we are having 3 channel(RGB). And if we take R = 0, G = 0 & B = 0, then the overall image will be black. Am I correct??
CodePudding user response:
The purple color comes from the default colormap being used in matplotib. If you want black-white, you should use the cmap='gray'
argument from the plt.imshow
function. (see documentation for more colormaps.) However, this implies you don't have dedicated red, green, and blue (RGB) channels but a single channel. (In the case of a single channel you can also use plt.matshow
.)
To be clear, a colormap maps values from your array to the pre-defined colors in the colormap.
In your second example, you again have one channel. Therefore, again the purple color from the default colormap will show.
Indeed in your third example you have three channels all with values 0 so now no colormap is used to map values of your array to colors. Hence the image is black.