w3resource

Read PNG image data into NumPy array using Python


18. Image File Read (PNG)

Write a NumPy program that read image data from a PNG file into a NumPy array using an image processing library like PIL or opencv.

Read PNG image data into NumPy array using Python

Sample Solution:

Python Code:

from PIL import Image
import numpy as np

# Define the path to the PNG file
image_path = 'image.png'

# Open the image file using PIL
image = Image.open(image_path)

# Convert the image to a NumPy array
image_array = np.array(image)

# Print the shape of the image array to verify
print('Image array shape:', image_array.shape)

# Display the image array (optional, requires matplotlib)
import matplotlib.pyplot as plt
plt.imshow(image_array)
plt.show()

Output:

Image array shape: (170, 132, 3)

Explanation:

  • Import Libraries:
    • Imported Image from the PIL library for image processing.
    • Imported numpy as np for handling arrays.
  • Define Image Path:
    • Set the path to the PNG file as image_path.
  • Open Image File:
    • Used Image.open to open the image file specified by image_path.
  • Convert Image to NumPy Array:
    • Converted the image object to a NumPy array using np.array.
  • Print Image Array Shape:
    • Printed the shape of the NumPy array to verify the conversion.
  • Display Image Array:
    • Optionally displayed the image using matplotlib.pyplot to visualize the array data.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to read image data from a PNG file into an array using an image library and then apply a grayscale transformation.
  • Write a Numpy program to import a PNG image as a NumPy array and then extract specific color channels for analysis.
  • Write a Numpy program to load a PNG image into an array and then perform edge detection using convolution filters.
  • Write a Numpy program to read an image file, convert it to a NumPy array, and then resize it using array slicing and interpolation.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Save and load NumPy arrays with MATLAB .mat files using SciPy.
Next: Save a NumPy array as an image file using Python.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.