Hands-On Image Processing with Python
上QQ阅读APP看书,第一时间看更新

Converting from one image mode into another

We can convert an RGB image into a grayscale image while reading the image itself. The following code does exactly that:

im = imread("images/parrot.png", as_gray=True)
print(im.shape)
#(362L, 486L)

Note that we can lose some information while converting into grayscale for some colored images. The following code shows such an example with Ishihara plates, used to detect color-blindness. This time, the rgb2gray() function is used from the color module, and both the color and the grayscale images are shown side by side. As can be seen in the following figure, the number 8 is almost invisible in the grayscale version:

im = imread("../images/Ishihara.png")
im_g = color.rgb2gray(im)
plt.subplot(121), plt.imshow(im, cmap='gray'), plt.axis('off')
plt.subplot(122), plt.imshow(im_g, cmap='gray'), plt.axis('off')
plt.show()

The next figure shows the output of the previous code—the colored image and the grayscale image obtained from it: