Converting a color image to grayscale is a must for any image processing task. It not only makes the image size lower but also helpful in identifying important edges and features. In this entire tutorial, you will know the various methods to convert image to grayscale in python.
Methods to Convert Image to Grayscale in Python
Before showing you the coding demonstration you must install the python image processing libraries. In our examples, I am using Pillow, scikit-image, and Opencv python module. So install them. Secondly, the image used for explaining the examples is below.
Method 1: Convert Color Image to Grayscale using Pillow module
The first method is the use of the pillow module to convert images to grayscale images. Firstly I will read the sample image and then do the conversion. In the pillow, there is a function to convert RGB image to Greyscale and it is an image.convert(‘L ‘). Here “L” is the mode. There are also other modes you can know more about in the pillow documentation.
Run the below lines of code to get the greyscale image.
from PIL import Image img = Image.open('demo-image.jpg').convert('L') img.save('pil-greyscale.png')
Method 2: Color Image to Grayscale image using scikit-image
The second module to convert color image to greyscale image is using the scikit-image. Here I will import io and color objects from the scikit-image. The io will be used for reading and saving the image. And the color will allow you to convert the color image to grayscale.
Copy, paste, and run the below codes.
from skimage import color from skimage import io read_image = io.imread('demo-image.jpg') img = color.rgb2gray(read_image) io.imsave("skimage-greyscale.png",img)
Method 3: Converting the image to greyscale using OpenCV
The third method to do the conversion is the use of OpenCV. Here again, I will first load the image and convert the image to grayscale in python using the cvtColor() function. Lastly, I will save the image to the disk using imwrite() method.
Just run the code given below and see the output.
import cv2 img = cv2.imread("demo-image.jpg") gray_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imwrite("opencv-greyscale.png",gray_image)
Greyscale Image conversion is a must before doing any further image processing. These are the simple but effective methods to convert images to grayscale in python. Hope you are now able to convert the image to greyscale after reading it. Even if you have any doubt and want to ask any query then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.