Matplotlib - 处理图像
Matplotlib - 处理图像
Section titled “Matplotlib - 处理图像”Matplotlib 的 image 模块以及 imshow 函数,允许您显示表示为 NumPy 数组的二维栅格图像(例如照片或热力图)。
加载图像数据
Section titled “加载图像数据”Matplotlib 的 matplotlib.image.imread() 可以原生加载 PNG 图像。对于其他格式(如 JPEG、TIFF 等),它依赖于 Pillow 库(PIL,Python Imaging Library 的一个友好分支)。如果需要处理各种图像格式,请确保 Pillow 已安装(pip install Pillow)。
import matplotlib.pyplot as pltimport matplotlib.image as mpimgimport numpy as np
try: # Load an image file into a NumPy array # 将图像文件加载到 NumPy 数组中 # Replace 'my_image.png' with the path to your image # 将 'my_image.png' 替换为您的图像路径 img_array = mpimg.imread('my_image.png') # For non-PNG, imread might use Pillow if installed # 对于非 PNG 格式,如果 Pillow 已安装,imread 可能会使用它
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 # 示例:100x100 的 RGB 图像 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 返回一个 NumPy 数组。数组的形状取决于图像类型:
- (M, N): 灰度图像。
- (M, N, 3): RGB 彩色图像(值通常为 0-1 的浮点数或 0-255 的 uint8)。
- (M, N, 4): RGBA 彩色图像(包括一个 Alpha/透明度通道)。
使用 imshow() 显示图像
Section titled “使用 imshow() 显示图像”ax.imshow() 方法(或 plt.imshow() 函数)是显示图像数据的主要函数。
# (Assuming img_array exists from the loading step)# (假设 img_array 已从加载步骤中存在)
fig, ax = plt.subplots()
# Display the image array# 显示图像数组img_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()此代码在 Matplotlib 图形窗口中显示加载的(或占位符)图像数据。
imshow() 的重要参数:
Section titled “imshow() 的重要参数:”X: 图像数据(NumPy 数组)。cmap: 用于灰度或单通道图像的色彩映射(例如,‘gray’,‘viridis’)。对于 RGB(A) 数据被忽略。aspect: 控制宽高比(‘auto’,‘equal’)。‘equal’ 确保像素是正方形的。origin: 将数组的[0, 0]索引放置在左上角(‘upper’)或左下角(‘lower’)。默认通常是 ‘upper’。interpolation: 如果显示分辨率与图像分辨率不同,用于插值像素的方法(例如,‘nearest’,‘bilinear’,‘bicubic’)。vmin,vmax: 设置色彩映射覆盖的数据范围。
保存图像数据
Section titled “保存图像数据”您可以使用 matplotlib.pyplot.imsave() 或 matplotlib.image.imsave() 将 NumPy 数组保存为图像文件。
# (Assuming img_array exists)# (假设 img_array 存在)
try: # Example: Save the array as a new PNG file, perhaps modified # 示例:将数组保存为新的 PNG 文件,可能已修改 # 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) # 基础 RGB 到灰度转换(如有需要,请调整公式) 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") # 图像成功保存为 saved_image.png
except Exception as e: print(f"Error saving image: {e}") # 保存图像时出错imsave 接受文件名、数组数据以及可选参数,例如 cmap、origin、vmin、vmax,它们的行为类似于 imshow。
在 Matplotlib 中处理图像本质上涉及操作 NumPy 数组。您可以使用 NumPy 或专门的库(如 Scikit-image 或 OpenCV)执行各种图像处理任务,然后在用 imshow 可视化结果之前进行处理。