How can I Python read image files without using imageio
or scikit-image
?
I want to read a PNG image in Python, but I noticed that the imread
function in scipy
is being deprecated, and it recommends using the imageio
library. However, I want to limit my usage of external libraries to scipy
, numpy
, and matplotlib
.
Are there any methods within Python
, scipy
, numpy
, or matplotlib
that allow reading images and are not deprecated?
Hey there! Based on my experience, if you’re looking to work within the libraries you mentioned, matplotlib.pyplot.imread
is a reliable option. It’s simple to use and reads images directly into a NumPy array. Here’s an example for how you can use it to python read image data:
import matplotlib.pyplot as plt
image = plt.imread("image.png")
print(image.shape)
It works well with PNG and a few other formats, so it’s a good starting point for your needs.
Great suggestion, Ian! To add to that, if you’re open to using another widely-used library that integrates seamlessly with NumPy, you could try Pillow. It’s often pre-installed and gives you flexibility while still allowing you to python read image files into NumPy arrays.
Here’s an example:
from PIL import Image
import numpy as np
image = Image.open("image.png")
image_array = np.array(image)
print(image_array.shape)
Pillow tends to support a broader range of formats than matplotlib.pyplot.imread
, so it’s a handy alternative if you need that versatility.
These are both excellent solutions, but let me dive into an edge case that might come up. If you’re working in older Python environments or have stringent limitations, you could use scipy.ndimage.imread
. It’s important to note that it’s deprecated, but it still lets you python read image data if you’re avoiding newer dependencies.
Here’s how you’d do it in such cases:
from scipy.ndimage import imread # Only for older versions of scipy
image = imread("image.png", mode='RGB')
print(image.shape)
That said, for long-term projects, I agree with Ian and Netra—matplotlib.pyplot.imread
or Pillow is your best bet since scipy.ndimage.imread
may not work in newer releases of scipy
. It’s good to future-proof your code!