Photo by Hitesh Choudhary on Unsplash
Creating visual representations using the Matplotlib library in Python.
Introduction to Matplotlib
The matplotlib library is extensively utilized for data visualization in Python. In this article, we will explore how to showcase, adjust, and store an image with the help of the 'matplotlib' library. By utilizing the 'image' module, we can effortlessly manipulate images in several ways. This includes making changes such as altering the colour, and size, cropping the image, and more. Additionally, we can save the modified image as a new file.
The article covers the following topics:
Importing the Libraries
Importing the Image Data Into Numpy Arrays
Displaying the Image
Selecting a part of the Image
Adding a Color Scale
Removing the Axes
Converting a Color Image into a Grayscale Image
Saving an Image
Plotting the Histogram of the Image Data
Importing the Matplotlib Library
We will start by importing the required libraries.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
We will utilize the 'image' submodule of the Matplotlib library, which provides support for fundamental image operations such as loading, rescaling, and displaying the image. For ease of use, we will alias it as 'mpimg'. Additionally, we will use the 'pyplot' submodule as it supports various kinds of plotting. To enable inline plotting, you can use the following code. This magic command showcases the plots immediately below the cells where you've coded your plotting command.
Importing the Image Data Into Numpy Arrays
To display an image, you first need to read the image. Images are comprised of pixels, and each pixel represents a color dot. In a color image, each pixel consists of three colors: red, green, and blue. The combination of these colors can produce any desired color.
When an image is saved on a computer, it is stored as an array of numbers. Each pixel can have a value ranging from 0 to 255, where 0 represents the darkest and 255 represents the brightest.
For grayscale (black and white) images, each pixel has a single value in the range of 0 to 1. In grayscale images, 0 represents black, and 1 represents white. The values in the range between 0 and 1 represent various shades of grey.
In this article, we will plot the following image.
The image we will be using is a 32-bit PNG image with RGBA format, meaning each pixel is comprised of 32 bits with 8 bits for each channel. The R stands for Red color, G stands for Green color, B stands for Blue color, and A stands for the alpha channel, which indicates the transparency of a color. The alpha channel can have a value between 0.0 to 1.0, where 0 represents fully transparent and 1 represents fully opaque.
You can download this image from the following link: unsplash.com/photos/t0dIdyfHHms
To read the image file into an array, we will use the 'imread' method. It accepts two parameters: 'fname' and 'format'. 'fname' denotes the name of the image file. If the image file is in the same working directory, you can provide just the file name. Otherwise, you'll need to provide the path of the file along with its name.
The 'format' parameter specifies the format of the image file, and it is optional. If you don't provide the format, it will be extracted from the name of the image file.
#Reading the image
img = mpimg.imread('Taj.png')
#Printing the image array
print(img)
[[0.41568628 0.5294118 0.31764707 1. ]
[0.41960785 0.5294118 0.29803923 1. ]
[0.38431373 0.48235294 0.21568628 1. ]
...
[0.5254902 0.46666667 0.2509804 1. ]
[0.5686275 0.50980395 0.29411766 1. ]
[0.56078434 0.5019608 0.28627452 1. ]]]
This function returns a multidimensional NumPy array. The shape of the returned NumPy array depends on the type of the image, that is, whether the image is grayscale, RGB, or RGBA (RGB with an alpha channel to specify the opacity for the color).
The following code will display the shape of the image data.
print(img.shape)
(853, 640, 4)
Each pixel of the RGBA image is represented by an inner list, containing 4 values. The first value corresponds to the Red color channel, the second to the Green color channel, the third to the Blue color channel, and the fourth to the alpha channel, which controls opacity.
The data type of the values in the lists is float32 because matplotlib rescales the 8-bit data from each channel to floating-point values between 0.0 and 1.0. For RGB and RGBA images, matplotlib supports both float32 and uint8 data types. However, for grayscale images, matplotlib only supports float32.
Displaying the Image Using Matplotlib
With the image data in the NumPy array, we can use the 'imshow()' function to display it. We will use the 'pyplot' object as it simplifies the process of manipulating the plot. You can plot any NumPy array using this function, whether it contains RGB data, RGBA data, or 2-D scalar data (for grayscale images).
#Displaying the image
imgplot = plt.imshow(img)
Selecting a part of the Image
Axes are helpful if you want to select only a part of the image. You can use them as a guide while slicing the image.
For the given image, if you want to display only the Taj Mahal excluding the other parts of the image then you can use the ticks and labels displayed on the axes to decide which part of the image to slice. The third parameter shows the color channels. Here, we are selecting all the color channels.
selected_part = img[290:680 , 10:630 , : ]
plt.imshow(selected_part)
You can see that the image has been perfectly sliced and it’s showing only the Taj Mahal.
Adding a Color Scale using Matplotlib
If you want to know what value a specific color represents, you can add a color bar to the image using the following code:
imgplot = plt.imshow(img)
plt.colorbar()
We can see that a color bar is added to the right of the image and it displays values in the range of 0 to 1 for all the colors of the given image.
Removing the Axes with Matplotlib
If you do not want the numbered axes to be displayed in your image, you can get rid of the axes by using the ‘axis’ method and setting its parameter value as ‘off’.
plt.axis("off")
plt.imshow(img)
After executing the code, we can see that the axes are gone in the above image.
Converting a Color Image into a Grayscale Image
We can use slicing to turn the 3-D array of RGB color images into a 2-D array of a grayscale images and thus convert the color image into a grayscale image.
We will select only one of the three dimensions and the color map parameter as ‘gray’ in the following code to make it a grayscale image.
grayscale_img = img[:, :, 0]
plt.imshow(grayscale_img, cmap='gray')
Saving an Image
You can apply different pseudocolor schemes to the image. It makes it easy to visualize the image data by enhancing the contrast. If you don’t provide a colormap value, the default value ‘viridis’ is used. Let’s see how it affects the image by executing the following code.
plt.imshow(grayscale_img)
There are many colormap values that you can choose and apply to your image. For more information on colormap values you can visit https://matplotlib.org/stable/tutorials/colors/colormaps.html
Let’s see how the image changes after applying the cmap value ‘hot’. We will also save the changed image into a file. If you don’t provide the path for the file, it will be saved in the current working directory.
plt.imshow(grayscale_img,cmap ='hot')
plt.savefig("New_Image.png")
After executing the above code, a new image file with the name ‘New_Image.png’ gets created and stored in the current working directory.
Plotting Histogram of the Image Data with Matplotlib
You can also plot the histogram of the image data using the hist() function. It’s useful for examining a specific range of data to enhance or expand the contrast in a particular region.
Let’s create and plot a histogram of the grayscale image that we created above using the following code.
plt.hist(img.ravel())
(array([ 10133., 21041., 22268., 158668., 200710., 38916., 21800.,
32729., 34041., 5614.]),
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ],
dtype=float32),
)
ravel function returns a flattened array of the image data.
https://matplotlib.org/stable/tutorials/introductory/images.html
Conclusion:
Great! It looks like you have summarized the key takeaways from the article on using the ‘image’ module of matplotlib to perform various operations on images. From the article, you learned how to plot and modify images, including turning an image into grayscale, selecting a part of the image, displaying a color bar, applying color schemes, and saving the modified image. Additionally, you learned how to plot the histogram of image data.