OpenCV色彩过滤与物体追踪实战 - 第4节
4. 图像基本操作
读取 · 显示 · 保存 · 属性 (shape, dtype)
4.1 读取图像
使用 OpenCV 的 cv2.imread() 函数将图像从磁盘加载为 NumPy 数组。支持彩色、灰度、原始数据等模式。
图4-1 图像读取流程:文件 → 数组
import cv2
# 读取彩色图像 (BGR顺序)
img = cv2.imread('example.jpg')
# 读取灰度图像
gray = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
4.2 显示图像
利用 cv2.imshow() 在窗口中显示图像,配合 waitKey() 保持窗口响应。
图4-2 显示图像:数组 → 窗口
cv2.imshow('Image Window', img)
cv2.waitKey(0) # 等待按键
cv2.destroyAllWindows() # 关闭所有窗口
4.3 保存图像
使用 cv2.imwrite() 将数组编码并写入文件。支持 PNG、JPEG 等格式。
图4-3 保存图像:数组 → 文件
success = cv2.imwrite('result.png', img)
if success:
print("图像保存成功")
4.4 图像属性 (shape, dtype)
图像本质是 NumPy 数组,通过 .shape 获取尺寸与通道数,.dtype 获取数据类型。
| 属性 | 含义 | 示例值 |
|---|---|---|
img.shape | 高度、宽度、通道数 (H, W, C) | (480, 640, 3) |
img.dtype | 数组元素类型 | uint8 |
img.size | 像素总数 (H*W*C) | 921600 |
图4-4 图像数组属性示意
print("图像形状:", img.shape) # (480, 640, 3)
print("数据类型:", img.dtype) # uint8
print("像素总数:", img.size) # 921600
4.5 综合小例
读取、显示、打印属性并保存灰度版本。
import cv2
img = cv2.imread('scene.jpg')
print(f"原始 shape: {img.shape}, dtype: {img.dtype}")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray', gray)
cv2.imwrite('scene_gray.png', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()