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!