Home > Backend Development > Python Tutorial > How to Convert RGB Images to Grayscale in Python Using Pillow and Matplotlib?

How to Convert RGB Images to Grayscale in Python Using Pillow and Matplotlib?

Mary-Kate Olsen
Release: 2024-12-01 07:49:10
Original
504 people have browsed it

How to Convert RGB Images to Grayscale in Python Using Pillow and Matplotlib?

Converting RGB Images to Grayscale in Python

In image processing, converting RGB images to grayscale is a common operation. While numerous approaches exist, finding the built-in method in the powerful libraries like NumPy or Matplotlib can simplify your task.

Pillow Library:

A straightforward solution is to use the Python Image Library (Pillow). It offers a convenient method to convert RGB images to grayscale:

from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
Copy after login

This code reads the RGB image, converts it to grayscale, and saves the resulting image.

Using Matplotlib with a Formula:

Another approach is to use the formula Y' = 0.2989 R 0.5870 G 0.1140 B to convert RGB images to grayscale. With Matplotlib, you can implement this as:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])

img = mpimg.imread('image.png')     
gray = rgb2gray(img)    
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
plt.show()
Copy after login

This code loads the image, converts it to grayscale using the formula, and displays the grayscale image.

The above is the detailed content of How to Convert RGB Images to Grayscale in Python Using Pillow and Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template