How do I Display a Grayscale Image Correctly with Matplotlib.pyplot.imshow()?

Barbara Streisand
Release: 2024-11-04 06:44:29
Original
164 people have browsed it

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:

  1. Import the necessary libraries: numpy for numerical operations and matplotlib.pyplot for image plotting.
  2. Load the image using PIL's Image.open().
  3. Convert the image to grayscale using convert("L").
  4. Convert the grayscale image to a NumPy array using np.asarray().
  5. Use matplotlib.pyplot.imshow() to display the grayscale image. Ensure to specify cmap='gray' to enforce the grayscale representation.

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!