Convert image to grayscale Python
In this post, you will learn how to convert an image to grayscale using the Python programming language.
A grayscale (or graylevel) image is just one in which the only colours are shades of dark. The reason for differentiating such images from any other sort of color image is that less data should be accommodated at every pixel. The grayscale image contains only black, white, and gray colors, in which gray has multiple levels.
Convert image to grayscale using Pillow library
The Pillow and PIL (Python Imaging Library) are the same. The PIL was used with Python2. Pillow is a fork of the PIL repository which is currently compatible with Python3. This library is mostly used for image opening, processing, and transforming.
To install Pillow on Windows, open a terminal window and run the following command.
pip install pillow
The most common module for image handling is the Image module. Here, we have used the open() method of this module to read an image. Python Pillow provides the convert() method for color conversion. The following code reads an image and converts it to grayscale. We have also saved the generated grayscale image using the save() method.
from PIL import Image
img = Image.open('naturalimg.jpg')
img_cov = img.convert('L')
#show image
img.show()
img_cov.show()
#save image
img_cov.save("naturalimg_gray.jpg")
Output of the above code:
Convert image to grayscale using scikit-image Module
Scikit-learn is a free software machine learning library for the Python programming language. It supports Python numerical and scientific libraries, of which color.rgb2gray() is one of them. The color.rgb2gray() takes an image in RGB format as input and returns a grayscale copy of the input image.
from skimage import io
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2gray
from skimage import data
path = "natural.png"
orig_img = io.imread(path)
grayscale_img = rgb2gray(orig_img)
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()
ax[0].imshow(orig_img)
ax[0].set_title("Original image")
ax[1].imshow(grayscale_img, cmap=plt.cm.gray)
ax[1].set_title("Grayscale image")
fig.tight_layout()
plt.show()
Output of the above code:
Convert image to grayscale using OpenCV Library
OpenCV is a free, open source library that is used for computer vision. It provides good support for Machine Learning, Face Recognition, Deep Learning, etc. The cv2.imread() method loads an image from the specified file. For using this, first we have to import the cv2 library in the Python file using the import statement. The cv2.imread(path, flag) method accepts two parameters: path and flag. If the flag value of the cv2.imread() method is equal to 1, it will read the image excluding the alpha channel. If the flag value is equal to 0, it will read the image as grayscale, and if it is equal to -1, the method will read the image including the alpha channel information.
# import opencv
import cv2
# Load the input image
image = cv2.imread('natural.jpg')
cv2.imshow('Original', image)
cv2.waitKey(0)
# Use the cvtColor() function to grayscale the image
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale', gray_image)
cv2.waitKey(0)
# Window shown waits for any key pressing event
cv2.destroyAllWindows()
Output of the above code:
Convert image to grayscale using Matplotlib Library
Matplotlib is a Python 2D plotting library and, furthermore, the most well-known one. The greater part of the individuals start their Data Visualization venture with Matplotlib. The given example demonstrates how we can implement the RGB to grayscale conversion formula in Python using the Matplotlib library.
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('kittens.jpg')
R, G, B = img[:,:,0], img[:,:,1], img[:,:,2]
imgGray = 0.2989 * R + 0.5870 * G + 0.1140 * B
plt.imshow(imgGray, cmap='gray')
plt.show()
Output of the above code:
Related Articles
Python OpenCV Image FilteringPython OpenCV Histogram of Color Image
Detect Specific Color From Image using Python OpenCV
Arithmetic Operations on Images using Python OpenCV
Python OpenCV Histogram of Grayscale Image
Python OpenCV Overlaying or Blending Two Images
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
Image Thresholding Python OpenCV
Python OpenCV Histogram Equalization
How to extract text from image using Python
Human Body Detection Program In Python OpenCV
How to add background image in Python Tkinter
Python program to map two lists into a dictionary
Python OpenCV Gaussian Blur Filtering
Harris Corner Detection using Python OpenCV
How to display image from database in Django