如何仅用scipy、numpy、matplotlib读取PNG图像(规避弃用方法)
不依赖imageio/scikit-image读取PNG图像的可行方案
Got it, let's break down how to handle this since scipy's old image reading functions are deprecated, and you want to stick to scipy, numpy, and matplotlib only. The practical, non-deprecated solution here relies entirely on matplotlib's built-in tools.
1. 使用matplotlib.pyplot.imread
This is the most straightforward and reliable option. Matplotlib's imread fully supports PNG (plus JPG, BMP, etc.) and returns a numpy array directly—perfect for your library stack.
Here's a complete working example:
import matplotlib.pyplot as plt import numpy as np # Replace with your actual PNG file path image_path = "your_image.png" # Read the image into a numpy array img_array = plt.imread(image_path) # Verify the output details print(f"图像形状: {img_array.shape}") # 对于RGB图是(H, W, 3),带透明通道则是(H, W, 4) print(f"数据类型: {img_array.dtype}") # 通常是uint8或float32(0-1范围) # 可选:显示图像确认读取结果 plt.imshow(img_array) plt.axis("off") # 隐藏坐标轴让显示更干净 plt.show()
关于输出的补充说明
- 如果读取的图像是
float32类型(数值范围0-1),你可以按需转换为常用的uint8(0-255范围):if img_array.dtype == np.float32: img_array = (img_array * 255).astype(np.uint8)
关于scipy的情况
遗憾的是,scipy所有内置的图像读取函数都已被弃用,官方明确推荐改用imageio。既然你想避开imageio,scipy目前没有合规的、未被弃用的PNG读取方法,所以matplotlib是当前最适配你的需求的选择。
内容的提问来源于stack exchange,提问作者Gerges
相关产品推荐
相关产品推荐

