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
Release: 2024-12-04 19:31:16
Original
907 people have browsed it

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')
Copy after login

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()
Copy after login

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!

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