Matplotlib - Working with Images
Matplotlib - Working with Images
Section titled “Matplotlib - Working with Images”Matplotlib’s image module, along with the imshow function, allows you to display 2D raster images (like photographs or heatmaps) represented as NumPy arrays.
Loading Image Data
Section titled “Loading Image Data”Matplotlib’s matplotlib.image.imread() can load PNG images natively. For other formats (like JPEG, TIFF, etc.), it relies on the Pillow library (a friendly fork of PIL, the Python Imaging Library). Ensure Pillow is installed (pip install Pillow) if you need to work with various image formats.
import matplotlib.pyplot as pltimport matplotlib.image as mpimgimport numpy as np
try: # Load an image file into a NumPy array # Replace 'my_image.png' with the path to your image img_array = mpimg.imread('my_image.png') # For non-PNG, imread might use Pillow if installed
print(f"Image loaded successfully. Shape: {img_array.shape}, Data type: {img_array.dtype}")
except FileNotFoundError: print("Error: Image file not found. Please provide a valid path.") # Create a placeholder array if image loading fails, for demonstration img_array = np.random.rand(100, 100, 3) # Example: 100x100 RGB image print("Using a random placeholder image instead.")except Exception as e: print(f"Error loading image: {e}") img_array = np.random.rand(100, 100, 3) print("Using a random placeholder image instead.")imread returns a NumPy array. The shape of the array depends on the image type:
- (M, N): Grayscale image.
- (M, N, 3): RGB color image (values typically 0-1 float or 0-255 uint8).
- (M, N, 4): RGBA color image (includes an alpha/transparency channel).
Displaying Images with imshow()
Section titled “Displaying Images with imshow()”The ax.imshow() method (or plt.imshow()) is the primary function for displaying image data.
# (Assuming img_array exists from the loading step)
fig, ax = plt.subplots()
# Display the image arrayimg_plot = ax.imshow(img_array)
ax.set_title('Image Display with imshow()')
# Optional: Hide axes ticks and labels for cleaner image display# ax.axis('off')
plt.show()This code displays the loaded (or placeholder) image data in a Matplotlib figure window.
Important imshow() Parameters:
Section titled “Important imshow() Parameters:”X: The image data (NumPy array).cmap: Colormap to use for grayscale or single-channel images (e.g., ‘gray’, ‘viridis’). Ignored for RGB(A) data.aspect: Controls the aspect ratio (‘auto’, ‘equal’). ‘equal’ ensures pixels are square.origin: Places the[0, 0]index of the array in the upper (‘upper’) or lower (‘lower’) left corner. Default is typically ‘upper’.interpolation: Method used to interpolate pixels if the display resolution differs from the image resolution (e.g., ‘nearest’, ‘bilinear’, ‘bicubic’).vmin,vmax: Set the data range that the colormap covers.
Saving Image Data
Section titled “Saving Image Data”You can save a NumPy array as an image file using matplotlib.pyplot.imsave() or matplotlib.image.imsave().
# (Assuming img_array exists)
try: # Example: Save the array as a new PNG file, perhaps modified # Let's create a grayscale version for saving if img_array.ndim == 3 and img_array.shape[2] >= 3: # Basic RGB to grayscale conversion (adjust formula if needed) gray_img = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]) elif img_array.ndim == 2: gray_img = img_array else: print("Cannot convert image to grayscale for saving example.") gray_img = None
if gray_img is not None: plt.imsave("saved_image.png", gray_img, cmap='gray', origin='upper') print("Image saved successfully as saved_image.png")
except Exception as e: print(f"Error saving image: {e}")imsave takes the filename, the array data, and optional parameters like cmap, origin, vmin, vmax which behave similarly to imshow.
Working with images in Matplotlib fundamentally involves manipulating NumPy arrays. You can perform various image processing tasks using NumPy or dedicated libraries like Scikit-image or OpenCV before visualizing the results with imshow.