【python】使用NumPy和Matplotlib,手动实现图像镜像变换
·
安装必要的库
pip install numpy matplotlib
完整实现代码
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def read_image(path):
try:
image_array = mpimg.imread(path)
return image_array
except FileNotFoundError:
print(f"错误:找不到文件{path}")
return None
except Exception as e:
print(f"读图时发生错误:{e}")
return None
"""水平镜像变换"""
def horizontal_mirror(image_array):
# 获取图像尺寸
if len(image_array.shape) == 3: # 彩色图像
height, width, channels = image_array.shape
# 创建空的结果数组
mirrored = np.zeros_like(image_array)
# 使用矩阵操作实现水平镜像
for i in range(height):
mirrored[i, :, :] = image_array[i, ::-1, :] # 修正:::-1 而不是 ::i
return mirrored
else: # 灰度图像
height, width = image_array.shape
mirrored = np.zeros_like(image_array)
for i in range(height):
mirrored[i, :] = image_array[i, ::-1]
return mirrored
"""垂直镜像变换"""
def vertical_mirror(image_array):
# 获取图像尺寸
if len(image_array.shape) == 3: # 彩色图像
height, width, channels = image_array.shape
# 创建空的结果数组
mirrored = np.zeros_like(image_array)
# 对于每一列,将像素从下到上复制
for j in range(width): # 修正:应该是width而不是height
mirrored[:, j, :] = image_array[::-1, j, :]
return mirrored
else: # 灰度图像
height, width = image_array.shape
mirrored = np.zeros_like(image_array)
for j in range(width):
mirrored[:, j] = image_array[::-1, j]
return mirrored
def horizontal_mirror_optimized(image_array):
if len(image_array.shape) == 3:
return image_array[:, ::-1, :]
else:
return image_array[:, ::-1]
def vertical_mirror_optimized(image_array):
if len(image_array.shape) == 3:
return image_array[::-1, :, :]
else:
return image_array[::-1, :]
def display_images(original, horizontal, vertical, both):
plt.figure(figsize=(12, 10))
plt.subplot(2, 2, 1)
plt.imshow(original, cmap='gray' if len(original.shape) == 2 else None)
plt.title('原始图像')
plt.axis('off')
plt.subplot(2, 2, 2)
plt.imshow(horizontal, cmap='gray' if len(horizontal.shape) == 2 else None)
plt.title('水平镜像')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.imshow(vertical, cmap='gray' if len(vertical.shape) == 2 else None)
plt.title('垂直镜像')
plt.axis('off')
plt.subplot(2, 2, 4)
plt.imshow(both, cmap='gray' if len(both.shape) == 2 else None)
plt.title('水平+垂直镜像')
plt.axis('off')
plt.tight_layout()
plt.show()
def main():
# 读取图像
path = "your_image.jpg" # 确保这个文件存在
image_array = read_image(path)
if image_array is None:
print("无法读取图像,程序退出")
return # 只有读取失败时才返回
print(f"图像尺寸:{image_array.shape}")
print(f"像素值范围:{image_array.min()} 到 {image_array.max()}")
# 执行镜像变换(使用优化版本,更快)
horizontal_mirrored = horizontal_mirror_optimized(image_array)
vertical_mirrored = vertical_mirror_optimized(image_array)
both_mirrored = vertical_mirror_optimized(horizontal_mirror_optimized(image_array))
# 显示结果
display_images(image_array, horizontal_mirrored, vertical_mirrored, both_mirrored)
if __name__ == "__main__":
main()
代码说明
- 水平镜像变换:使用NumPy的切片操作
[:, ::-1, :],其中::-1表示将列顺序反转 - 垂直镜像变换:使用切片操作
[::-1, :, :],其中::-1表示将行顺序反转 - 同时变换:先水平后垂直镜像,相当于旋转180度
1. 图像读取
使用matplotlib.image.imread()函数读取图像,返回一个NumPy数组。注意:
- 对于PNG图像,像素值范围是0-1
- 对于JPEG图像,像素值范围是0-255
2. 镜像变换实现
提供了两种实现方式:
基础版本(使用循环):
def horizontal_mirror(image_array):
height, width, channels = image_array.shape
mirrored = np.zeros_like(image_array)
for i in range(height):
mirrored[i, :, :] = image_array[i, ::-1, :]
return mirrored
优化版本(使用NumPy高级索引):
def horizontal_mirror_optimized(image_array):
return image_array[:, ::-1, :]
添加对灰度图像的支持:检查图像维度并分别处理彩色和灰度图像
在显示图像时添加cmap参数:确保灰度图像正确显示
3. 图像显示和保存
使用Matplotlib显示和保存图像结果。
使用说明
- 将代码中的
"your_image.jpg"替换为你要处理的图像路径 - 运行代码,将会显示原始图像和三种镜像变换的结果
- 如果需要保存结果,取消注释代码末尾的保存部分
注意事项
-
如果图像是灰度图(只有高度和宽度两个维度),需要先将其转换为三通道图像:
if len(image_array.shape) == 2: image_array = np.stack([image_array] * 3, axis=-1) -
处理不同格式的图像时需要注意像素值范围:
- PNG图像:0-1
- JPEG图像:0-255
更多推荐
所有评论(0)