I am completely new to Python. I took a color image. Then converted it into gray scale image. So far it was good. But when I tried to convert this gray scale to binary image, I got yellow and purple color image instead of white and black.
import matplotlib.pyplot as plt
import numpy as np
painting=plt.imread("ff.jpg")
print(painting.shape)
print("The image consists of %i pixels" % (painting.shape[0] * painting.shape[1]))
plt.imshow(painting);
#This displayed by color image perfectly
from skimage import data, io, color
painting_gray = color.rgb2gray(painting)
print(painting_gray)
io.imshow(painting_gray)
print("This is the Gray scale version of the original image")
#This displayed my gray scale image perfectly
#Now comes the code for binary image:
num = np.array(painting_gray)
print(num)
bin= num >0.5
bin.astype(np.int)
plt.imshow(bin)
#The display showed an image with yellow and purple color instead of white and black
The image plots I have obtained are:
Please help me to get black and white binary image.
It is because imshow
uses a default colormap, called viridis. The pixel color is selected from this color map, using the scale of the pixel values from min(img) to max(img).
There more than one way to deal with this:
Specify color map in imshow
:
plt.imshow(bin, cmap='gray', vmin=0, vmax=255)
Select color map:
plt.gray()
Another way to select color map:
plt.colormap('gray')
Side note: bin
is a function used for converting binary numbers, so using it as a variable name can potentially cause problems in your code.