Home >Backend Development >Python Tutorial >How to Efficiently Convert RGB Images to Grayscale in Python?

How to Efficiently Convert RGB Images to Grayscale in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 19:31:16930browse

How to Efficiently Convert RGB Images to Grayscale in Python?

Converting RGB Images to Grayscale in Python

Question:

How can I efficiently convert an RGB image into grayscale using Python?

Problem Description:

Attempting to convert an RGB image to grayscale using the imread function in matplotlib, but encountering limitations in the available operations. Manual implementation of RGB to grayscale conversion found to be inefficient. Seeking a professional, built-in solution for this common image processing task.

Answers:

Using Pillow:

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

Using Matplotlib and the RGB to Grayscale Formula:

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()

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

Statement:
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