Home  >  Article  >  Backend Development  >  How to Display Grayscale Images Correctly in Matplotlib?

How to Display Grayscale Images Correctly in Matplotlib?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 04:41:01768browse

How to Display Grayscale Images Correctly in Matplotlib?

Displaying Images as Grayscale

Many image manipulation tasks often require grayscale images for ease of processing. Displaying grayscale images using Matplotlib's imshow() function can be challenging when the image is accidentally rendered as a colormap.

To resolve this issue and display a grayscale image correctly, follow these steps:

  1. Import necessary libraries: Load important libraries such as NumPy for image processing, Matplotlib for plotting, and PIL for image manipulation.
  2. Read and convert image to grayscale: Use PIL's Image.open() function to read the image from a file. Subsequently, convert the image to grayscale using convert("L").
  3. Convert image to matrix: Transform the grayscale image into a numerical matrix using SciPy's scipy.misc.fromimage().
  4. Specify grayscale display: When displaying the matrix using matplotlib.pyplot.imshow(), explicitly specify the colormap as 'gray' to render the image in grayscale. Adjust the 'vmin' and 'vmax' parameters to set the value range for grayscale intensities.
<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, to display the inverse grayscale, simply change the cmap parameter to 'gray_r'.

The above is the detailed content of How to Display Grayscale Images Correctly in Matplotlib?. 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