简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索

活动公告

通知:为庆祝网站一周年,将在5.1日与5.2日开放注册,具体信息请见后续详细公告
04-22 00:04
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

numpy输出图片完整教程深入浅出讲解如何使用Python科学计算库处理图像数据从数组定义到可视化输出包括matplotlib集成和实际代码示例助您快速上手

SunJu_FaceMall

3万

主题

1158

科技点

3万

积分

白金月票

碾压王

积分
32796

立华奏

发表于 2025-10-1 22:50:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

NumPy是Python科学计算的核心库,提供了高性能的多维数组对象以及用于处理这些数组的工具。在图像处理领域,NumPy扮演着至关重要的角色,因为图像本质上就是多维数组(矩阵)。本教程将深入浅出地介绍如何使用NumPy处理图像数据,从基础的数组定义到复杂的图像操作,再到使用Matplotlib进行可视化输出。

NumPy基础

安装NumPy

在开始之前,确保已安装NumPy库。如果尚未安装,可以通过以下命令安装:
  1. pip install numpy
复制代码

创建NumPy数组

NumPy的核心是ndarray对象,它是一个快速、灵活的大型数据集容器。让我们从创建基本的数组开始:
  1. import numpy as np
  2. # 创建一维数组
  3. arr1d = np.array([1, 2, 3, 4, 5])
  4. print("一维数组:")
  5. print(arr1d)
  6. # 创建二维数组
  7. arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  8. print("\n二维数组:")
  9. print(arr2d)
  10. # 创建特定数组
  11. zeros = np.zeros((3, 3))  # 全零数组
  12. ones = np.ones((2, 4))    # 全一数组
  13. random = np.random.rand(3, 3)  # 随机数组
  14. print("\n全零数组:")
  15. print(zeros)
  16. print("\n全一数组:")
  17. print(ones)
  18. print("\n随机数组:")
  19. print(random)
复制代码

数组属性和操作

了解数组的基本属性对于图像处理至关重要:
  1. # 获取数组属性
  2. arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  3. print("数组形状:", arr.shape)  # 数组维度
  4. print("数组大小:", arr.size)   # 元素总数
  5. print("数组类型:", arr.dtype)  # 数据类型
  6. # 改变数组形状
  7. reshaped = arr.reshape(1, 9)  # 将3x3数组变为1x9数组
  8. print("\n重塑后的数组:")
  9. print(reshaped)
  10. # 数组切片
  11. print("\n第一行:", arr[0])     # 获取第一行
  12. print("\n第一列:", arr[:, 0])  # 获取第一列
  13. print("\n子数组:")
  14. print(arr[0:2, 0:2])          # 获取左上角的2x2子数组
复制代码

图像数据与NumPy数组的关系

在计算机中,图像可以表示为多维数组。对于灰度图像,它是一个二维数组,其中每个元素代表一个像素的亮度值。对于彩色图像,它通常是一个三维数组,其中前两个维度表示空间位置(高度和宽度),第三个维度表示颜色通道(通常是红色、绿色和蓝色,即RGB)。

让我们创建一个简单的灰度图像和彩色图像:
  1. # 创建一个简单的灰度图像(8x8像素)
  2. gray_image = np.zeros((8, 8), dtype=np.uint8)
  3. gray_image[2:6, 2:6] = 255  # 在中心创建一个白色方块
  4. # 创建一个简单的彩色图像(8x8像素,RGB)
  5. color_image = np.zeros((8, 8, 3), dtype=np.uint8)
  6. color_image[2:6, 2:6, 0] = 255  # 红色通道
  7. color_image[2:6, 2:6, 1] = 0    # 绿色通道
  8. color_image[2:6, 2:6, 2] = 0    # 蓝色通道
  9. print("灰度图像数组:")
  10. print(gray_image)
  11. print("\n彩色图像数组形状:", color_image.shape)
复制代码

使用NumPy读取和处理图像

虽然NumPy本身不提供直接读取图像文件的功能,但我们可以结合其他库(如PIL或OpenCV)来读取图像,并将其转换为NumPy数组进行处理。

使用PIL读取图像

首先,确保安装PIL库:
  1. pip install pillow
复制代码

然后,使用以下代码读取图像:
  1. from PIL import Image
  2. import numpy as np
  3. # 读取图像
  4. image_path = "example.jpg"  # 替换为你的图像路径
  5. img = Image.open(image_path)
  6. # 将PIL图像转换为NumPy数组
  7. img_array = np.array(img)
  8. print("图像数组形状:", img_array.shape)
  9. print("图像数据类型:", img_array.dtype)
复制代码

使用OpenCV读取图像

OpenCV是另一个流行的图像处理库,它直接将图像作为NumPy数组返回:
  1. pip install opencv-python
复制代码
  1. import cv2
  2. import numpy as np
  3. # 读取图像
  4. image_path = "example.jpg"  # 替换为你的图像路径
  5. img_array = cv2.imread(image_path)
  6. print("图像数组形状:", img_array.shape)
  7. print("图像数据类型:", img_array.dtype)
  8. # 注意:OpenCV默认以BGR顺序读取彩色图像,而不是RGB
  9. # 如果需要转换为RGB顺序:
  10. img_rgb = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)
复制代码

图像基本操作

裁剪图像

裁剪图像实际上是数组切片操作:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 裁剪图像 (y1:y2, x1:x2)
  8. height, width = img_array.shape[:2]
  9. cropped = img_array[int(height*0.2):int(height*0.8), int(width*0.2):int(width*0.8)]
  10. # 显示结果
  11. plt.figure(figsize=(12, 6))
  12. plt.subplot(1, 2, 1)
  13. plt.imshow(img_array)
  14. plt.title("原始图像")
  15. plt.subplot(1, 2, 2)
  16. plt.imshow(cropped)
  17. plt.title("裁剪后的图像")
  18. plt.show()
复制代码

调整图像大小

调整图像大小可以使用NumPy的插值方法,但更常见的是使用PIL或OpenCV提供的函数:
  1. from PIL import Image
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 使用PIL调整大小
  8. resized_pil = img.resize((img_array.shape[1]//2, img_array.shape[0]//2), Image.LANCZOS)
  9. resized_array = np.array(resized_pil)
  10. # 显示结果
  11. plt.figure(figsize=(12, 6))
  12. plt.subplot(1, 2, 1)
  13. plt.imshow(img_array)
  14. plt.title("原始图像")
  15. plt.subplot(1, 2, 2)
  16. plt.imshow(resized_array)
  17. plt.title("调整大小后的图像")
  18. plt.show()
复制代码

旋转图像

旋转图像可以使用NumPy的矩阵操作,但更简单的方法是使用PIL或OpenCV:
  1. from PIL import Image
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 使用PIL旋转图像
  8. rotated_pil = img.rotate(45)  # 旋转45度
  9. rotated_array = np.array(rotated_pil)
  10. # 显示结果
  11. plt.figure(figsize=(12, 6))
  12. plt.subplot(1, 2, 1)
  13. plt.imshow(img_array)
  14. plt.title("原始图像")
  15. plt.subplot(1, 2, 2)
  16. plt.imshow(rotated_array)
  17. plt.title("旋转后的图像")
  18. plt.show()
复制代码

翻转图像

翻转图像可以使用NumPy的切片操作:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 水平翻转
  8. flipped_h = np.fliplr(img_array)
  9. # 垂直翻转
  10. flipped_v = np.flipud(img_array)
  11. # 显示结果
  12. plt.figure(figsize=(15, 5))
  13. plt.subplot(1, 3, 1)
  14. plt.imshow(img_array)
  15. plt.title("原始图像")
  16. plt.subplot(1, 3, 2)
  17. plt.imshow(flipped_h)
  18. plt.title("水平翻转")
  19. plt.subplot(1, 3, 3)
  20. plt.imshow(flipped_v)
  21. plt.title("垂直翻转")
  22. plt.show()
复制代码

图像滤波和增强

灰度转换

将彩色图像转换为灰度图像:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 转换为灰度图像
  8. if len(img_array.shape) == 3:  # 如果是彩色图像
  9.     # 使用加权平均法转换
  10.     gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140])
  11.     gray = gray.astype(np.uint8)
  12. else:
  13.     gray = img_array  # 已经是灰度图像
  14. # 显示结果
  15. plt.figure(figsize=(12, 6))
  16. plt.subplot(1, 2, 1)
  17. plt.imshow(img_array)
  18. plt.title("原始图像")
  19. plt.subplot(1, 2, 2)
  20. plt.imshow(gray, cmap='gray')
  21. plt.title("灰度图像")
  22. plt.show()
复制代码

亮度调整

调整图像亮度:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 增加亮度
  8. brightness_factor = 1.5  # 亮度因子
  9. brightened = np.clip(img_array * brightness_factor, 0, 255).astype(np.uint8)
  10. # 降低亮度
  11. darkened = np.clip(img_array / brightness_factor, 0, 255).astype(np.uint8)
  12. # 显示结果
  13. plt.figure(figsize=(15, 5))
  14. plt.subplot(1, 3, 1)
  15. plt.imshow(img_array)
  16. plt.title("原始图像")
  17. plt.subplot(1, 3, 2)
  18. plt.imshow(brightened)
  19. plt.title("增加亮度")
  20. plt.subplot(1, 3, 3)
  21. plt.imshow(darkened)
  22. plt.title("降低亮度")
  23. plt.show()
复制代码

对比度调整

调整图像对比度:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 增加对比度
  8. contrast_factor = 1.5  # 对比度因子
  9. mean = np.mean(img_array)
  10. increased_contrast = np.clip((img_array - mean) * contrast_factor + mean, 0, 255).astype(np.uint8)
  11. # 降低对比度
  12. decreased_contrast = np.clip((img_array - mean) / contrast_factor + mean, 0, 255).astype(np.uint8)
  13. # 显示结果
  14. plt.figure(figsize=(15, 5))
  15. plt.subplot(1, 3, 1)
  16. plt.imshow(img_array)
  17. plt.title("原始图像")
  18. plt.subplot(1, 3, 2)
  19. plt.imshow(increased_contrast)
  20. plt.title("增加对比度")
  21. plt.subplot(1, 3, 3)
  22. plt.imshow(decreased_contrast)
  23. plt.title("降低对比度")
  24. plt.show()
复制代码

图像平滑(模糊)

图像平滑可以使用卷积操作实现:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. from scipy import ndimage
  5. # 读取图像
  6. img = Image.open("example.jpg")
  7. img_array = np.array(img)
  8. # 转换为灰度图像以便处理
  9. if len(img_array.shape) == 3:
  10.     gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  11. else:
  12.     gray = img_array
  13. # 均值滤波
  14. smoothed_mean = ndimage.uniform_filter(gray, size=5)
  15. # 高斯滤波
  16. smoothed_gaussian = ndimage.gaussian_filter(gray, sigma=2)
  17. # 显示结果
  18. plt.figure(figsize=(15, 5))
  19. plt.subplot(1, 3, 1)
  20. plt.imshow(gray, cmap='gray')
  21. plt.title("原始图像")
  22. plt.subplot(1, 3, 2)
  23. plt.imshow(smoothed_mean, cmap='gray')
  24. plt.title("均值滤波")
  25. plt.subplot(1, 3, 3)
  26. plt.imshow(smoothed_gaussian, cmap='gray')
  27. plt.title("高斯滤波")
  28. plt.show()
复制代码

边缘检测

边缘检测是图像处理中的常见任务,可以使用Sobel算子实现:
  1. import numpy as np
  2. from PIL import Image
  3. import matplotlib.pyplot as plt
  4. from scipy import ndimage
  5. # 读取图像
  6. img = Image.open("example.jpg")
  7. img_array = np.array(img)
  8. # 转换为灰度图像
  9. if len(img_array.shape) == 3:
  10.     gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  11. else:
  12.     gray = img_array
  13. # Sobel边缘检测
  14. sobel_h = ndimage.sobel(gray, axis=0)  # 水平边缘
  15. sobel_v = ndimage.sobel(gray, axis=1)  # 垂直边缘
  16. sobel = np.sqrt(sobel_h**2 + sobel_v**2)  # 合并边缘
  17. # 显示结果
  18. plt.figure(figsize=(15, 5))
  19. plt.subplot(1, 3, 1)
  20. plt.imshow(gray, cmap='gray')
  21. plt.title("原始图像")
  22. plt.subplot(1, 3, 2)
  23. plt.imshow(sobel_h, cmap='gray')
  24. plt.title("水平边缘")
  25. plt.subplot(1, 3, 3)
  26. plt.imshow(sobel, cmap='gray')
  27. plt.title("合并边缘")
  28. plt.show()
复制代码

使用Matplotlib进行图像可视化

Matplotlib是Python中最常用的绘图库,它可以很好地与NumPy集成,用于图像可视化。

安装Matplotlib

如果尚未安装Matplotlib,可以通过以下命令安装:
  1. pip install matplotlib
复制代码

基本图像显示

使用Matplotlib显示图像:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 显示图像
  8. plt.figure(figsize=(8, 6))
  9. plt.imshow(img_array)
  10. plt.title("图像显示示例")
  11. plt.axis('off')  # 关闭坐标轴
  12. plt.show()
复制代码

显示多个图像

在一个窗口中显示多个图像:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 创建不同的图像处理版本
  8. gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  9. flipped = np.fliplr(img_array)
  10. cropped = img_array[int(img_array.shape[0]*0.2):int(img_array.shape[0]*0.8),
  11.                    int(img_array.shape[1]*0.2):int(img_array.shape[1]*0.8)]
  12. # 创建2x2的子图
  13. plt.figure(figsize=(12, 10))
  14. # 原始图像
  15. plt.subplot(2, 2, 1)
  16. plt.imshow(img_array)
  17. plt.title("原始图像")
  18. plt.axis('off')
  19. # 灰度图像
  20. plt.subplot(2, 2, 2)
  21. plt.imshow(gray, cmap='gray')
  22. plt.title("灰度图像")
  23. plt.axis('off')
  24. # 翻转图像
  25. plt.subplot(2, 2, 3)
  26. plt.imshow(flipped)
  27. plt.title("翻转图像")
  28. plt.axis('off')
  29. # 裁剪图像
  30. plt.subplot(2, 2, 4)
  31. plt.imshow(cropped)
  32. plt.title("裁剪图像")
  33. plt.axis('off')
  34. plt.tight_layout()
  35. plt.show()
复制代码

直方图可视化

图像直方图是图像处理中的重要工具,可以显示图像中像素值的分布:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 转换为灰度图像
  8. if len(img_array.shape) == 3:
  9.     gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  10. else:
  11.     gray = img_array
  12. # 显示图像和直方图
  13. plt.figure(figsize=(12, 6))
  14. # 显示图像
  15. plt.subplot(1, 2, 1)
  16. plt.imshow(gray, cmap='gray')
  17. plt.title("灰度图像")
  18. plt.axis('off')
  19. # 显示直方图
  20. plt.subplot(1, 2, 2)
  21. plt.hist(gray.ravel(), bins=256, range=(0, 256), density=True, color='black', alpha=0.7)
  22. plt.title("像素值直方图")
  23. plt.xlabel("像素值")
  24. plt.ylabel("频率")
  25. plt.xlim(0, 256)
  26. plt.tight_layout()
  27. plt.show()
复制代码

彩色图像的直方图

对于彩色图像,可以分别显示每个颜色通道的直方图:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 确保是彩色图像
  8. if len(img_array.shape) == 3:
  9.     # 分离颜色通道
  10.     r = img_array[:, :, 0]
  11.     g = img_array[:, :, 1]
  12.     b = img_array[:, :, 2]
  13.    
  14.     # 显示图像和直方图
  15.     plt.figure(figsize=(15, 5))
  16.    
  17.     # 显示图像
  18.     plt.subplot(1, 2, 1)
  19.     plt.imshow(img_array)
  20.     plt.title("彩色图像")
  21.     plt.axis('off')
  22.    
  23.     # 显示直方图
  24.     plt.subplot(1, 2, 2)
  25.     plt.hist(r.ravel(), bins=256, range=(0, 256), density=True, color='red', alpha=0.5, label='Red')
  26.     plt.hist(g.ravel(), bins=256, range=(0, 256), density=True, color='green', alpha=0.5, label='Green')
  27.     plt.hist(b.ravel(), bins=256, range=(0, 256), density=True, color='blue', alpha=0.5, label='Blue')
  28.     plt.title("颜色通道直方图")
  29.     plt.xlabel("像素值")
  30.     plt.ylabel("频率")
  31.     plt.xlim(0, 256)
  32.     plt.legend()
  33.    
  34.     plt.tight_layout()
  35.     plt.show()
  36. else:
  37.     print("图像不是彩色图像")
复制代码

保存图像

使用Matplotlib保存图像:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 创建图形
  8. plt.figure(figsize=(8, 6))
  9. plt.imshow(img_array)
  10. plt.title("保存图像示例")
  11. plt.axis('off')
  12. # 保存图像
  13. plt.savefig("saved_image.png", dpi=300, bbox_inches='tight')
  14. plt.close()  # 关闭图形,避免显示
复制代码

实际应用案例

图像拼接

将多张图像拼接成一张大图:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取多张图像
  5. image_paths = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]  # 替换为实际路径
  6. images = [np.array(Image.open(path)) for path in image_paths]
  7. # 确保所有图像具有相同的高度
  8. min_height = min(img.shape[0] for img in images)
  9. resized_images = [img[:min_height, :] for img in images]
  10. # 水平拼接图像
  11. stitched_h = np.hstack(resized_images)
  12. # 垂直拼接图像
  13. min_width = min(img.shape[1] for img in images)
  14. resized_images_v = [img[:, :min_width] for img in images]
  15. stitched_v = np.vstack(resized_images_v)
  16. # 显示结果
  17. plt.figure(figsize=(15, 10))
  18. plt.subplot(2, 1, 1)
  19. plt.imshow(stitched_h)
  20. plt.title("水平拼接")
  21. plt.axis('off')
  22. plt.subplot(2, 1, 2)
  23. plt.imshow(stitched_v)
  24. plt.title("垂直拼接")
  25. plt.axis('off')
  26. plt.tight_layout()
  27. plt.show()
复制代码

批量处理图像

批量处理文件夹中的所有图像:
  1. import os
  2. import numpy as np
  3. from PIL import Image
  4. import matplotlib.pyplot as plt
  5. # 设置输入和输出文件夹
  6. input_folder = "input_images"  # 替换为实际路径
  7. output_folder = "output_images"  # 替换为实际路径
  8. # 创建输出文件夹(如果不存在)
  9. os.makedirs(output_folder, exist_ok=True)
  10. # 处理文件夹中的所有图像
  11. for filename in os.listdir(input_folder):
  12.     if filename.endswith(('.jpg', '.jpeg', '.png')):
  13.         # 读取图像
  14.         input_path = os.path.join(input_folder, filename)
  15.         img = Image.open(input_path)
  16.         img_array = np.array(img)
  17.         
  18.         # 应用图像处理(例如转换为灰度并调整大小)
  19.         if len(img_array.shape) == 3:
  20.             gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  21.         else:
  22.             gray = img_array
  23.             
  24.         # 调整大小
  25.         resized = Image.fromarray(gray).resize((gray.shape[1]//2, gray.shape[0]//2), Image.LANCZOS)
  26.         resized_array = np.array(resized)
  27.         
  28.         # 保存处理后的图像
  29.         output_path = os.path.join(output_folder, f"processed_{filename}")
  30.         Image.fromarray(resized_array).save(output_path)
  31.         
  32.         print(f"已处理并保存: {filename}")
  33. print("批量处理完成!")
复制代码

图像分割

简单的阈值分割示例:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. # 读取图像
  5. img = Image.open("example.jpg")
  6. img_array = np.array(img)
  7. # 转换为灰度图像
  8. if len(img_array.shape) == 3:
  9.     gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  10. else:
  11.     gray = img_array
  12. # 应用阈值分割
  13. threshold = 128  # 阈值
  14. binary = gray > threshold
  15. # 显示结果
  16. plt.figure(figsize=(15, 5))
  17. plt.subplot(1, 3, 1)
  18. plt.imshow(gray, cmap='gray')
  19. plt.title("原始灰度图像")
  20. plt.axis('off')
  21. plt.subplot(1, 3, 2)
  22. plt.imshow(binary, cmap='gray')
  23. plt.title(f"阈值分割 (阈值={threshold})")
  24. plt.axis('off')
  25. plt.subplot(1, 3, 3)
  26. plt.hist(gray.ravel(), bins=256, range=(0, 256), density=True, color='black', alpha=0.7)
  27. plt.axvline(x=threshold, color='red', linestyle='--')
  28. plt.title("直方图与阈值")
  29. plt.xlabel("像素值")
  30. plt.ylabel("频率")
  31. plt.xlim(0, 256)
  32. plt.tight_layout()
  33. plt.show()
复制代码

图像特征提取

提取图像的基本特征:
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from PIL import Image
  4. from scipy import ndimage
  5. # 读取图像
  6. img = Image.open("example.jpg")
  7. img_array = np.array(img)
  8. # 转换为灰度图像
  9. if len(img_array.shape) == 3:
  10.     gray = np.dot(img_array[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
  11. else:
  12.     gray = img_array
  13. # 计算基本特征
  14. mean_brightness = np.mean(gray)
  15. std_brightness = np.std(gray)
  16. min_brightness = np.min(gray)
  17. max_brightness = np.max(gray)
  18. # 计算梯度(边缘强度)
  19. grad_x = ndimage.sobel(gray, axis=0)
  20. grad_y = ndimage.sobel(gray, axis=1)
  21. gradient_magnitude = np.sqrt(grad_x**2 + grad_y**2)
  22. mean_gradient = np.mean(gradient_magnitude)
  23. # 显示结果
  24. plt.figure(figsize=(15, 5))
  25. plt.subplot(1, 3, 1)
  26. plt.imshow(gray, cmap='gray')
  27. plt.title("原始图像")
  28. plt.axis('off')
  29. plt.subplot(1, 3, 2)
  30. plt.imshow(gradient_magnitude, cmap='gray')
  31. plt.title("梯度幅度")
  32. plt.axis('off')
  33. plt.subplot(1, 3, 3)
  34. plt.text(0.1, 0.8, f"平均亮度: {mean_brightness:.2f}", transform=plt.gca().transAxes)
  35. plt.text(0.1, 0.7, f"亮度标准差: {std_brightness:.2f}", transform=plt.gca().transAxes)
  36. plt.text(0.1, 0.6, f"最小亮度: {min_brightness}", transform=plt.gca().transAxes)
  37. plt.text(0.1, 0.5, f"最大亮度: {max_brightness}", transform=plt.gca().transAxes)
  38. plt.text(0.1, 0.4, f"平均梯度: {mean_gradient:.2f}", transform=plt.gca().transAxes)
  39. plt.title("图像特征")
  40. plt.axis('off')
  41. plt.tight_layout()
  42. plt.show()
复制代码

总结与资源推荐

本教程详细介绍了如何使用NumPy处理图像数据,从基础的数组操作到复杂的图像处理技术。我们学习了:

1. NumPy基础知识和数组操作
2. 图像数据与NumPy数组的关系
3. 如何读取和处理图像
4. 图像的基本操作(裁剪、缩放、旋转、翻转)
5. 图像滤波和增强技术
6. 使用Matplotlib进行图像可视化
7. 实际应用案例

NumPy与图像处理的结合为科学计算和计算机视觉任务提供了强大的工具。通过掌握这些技术,您可以进一步探索更高级的图像处理和计算机视觉领域。

推荐资源

1. NumPy官方文档:https://numpy.org/doc/stable/
2. Matplotlib官方文档:https://matplotlib.org/stable/contents.html
3. Python图像处理手册:https://github.com/ActiveState/python-image-processing
4. OpenCV-Python教程:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html
5. Scikit-image文档:https://scikit-image.org/docs/stable/

希望本教程能帮助您快速上手使用NumPy处理图像数据。随着您对这些技术的掌握,您将能够解决更复杂的图像处理问题,并在计算机视觉领域取得更大的成就。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

手机版|联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.

>