Home >Backend Development >Python Tutorial >How do I Display a Grayscale Image Correctly with Matplotlib.pyplot.imshow()?
Achieving Grayscale Image Display with Matplotlib
When attempting to display a grayscale image using matplotlib.pyplot.imshow(), users may encounter difficulties resulting in the image being displayed as a colormap. To address this issue, it's crucial to understand the correct steps for grayscale image conversion.
In this case, the user has loaded the image and converted it to grayscale using PIL's Image.open().convert("L") function. However, the subsequent conversion to a matrix using scipy.misc.fromimage() introduced an unnecessary step and potentially corrupted the image's grayscale representation.
To display the grayscale image correctly, follow these steps:
Here's the sample code:
<code class="python">import numpy as np import matplotlib.pyplot as plt from PIL import Image fname = 'image.png' image = Image.open(fname).convert("L") arr = np.asarray(image) plt.imshow(arr, cmap='gray', vmin=0, vmax=255) plt.show()</code>
Alternatively, for displaying the inverse grayscale, switch the cmap argument to 'gray_r'.
The above is the detailed content of How do I Display a Grayscale Image Correctly with Matplotlib.pyplot.imshow()?. For more information, please follow other related articles on the PHP Chinese website!