第3章 · OpenCV基础入门
图像的读取、显示、保存 & 基本属性
本章是运动检测系统的基石。你将掌握 OpenCV 最核心的四个操作:imread、imshow、imwrite 以及图像属性 shape、dtype。所有后续的帧处理、运动分析都建立在这些基础之上。
▸ 图像读取→显示→保存 典型管线
1. 读取图像:cv.imread()
cv.imread(path, flags) 从磁盘加载图像,返回 NumPy 数组。常用 flag:
| 标志 | 整数值 | 含义 |
|---|---|---|
cv.IMREAD_COLOR | 1 | 默认,BGR 彩色 (忽略透明度) |
cv.IMREAD_GRAYSCALE | 0 | 单通道灰度 |
cv.IMREAD_UNCHANGED | -1 | 包含 alpha 通道 (BGRA) |
import cv2 as cv
# 读取彩色图像 (BGR)
img_color = cv.imread('scene.jpg', cv.IMREAD_COLOR)
# 读取灰度图像
img_gray = cv.imread('scene.jpg', cv.IMREAD_GRAYSCALE)
# 读取包含透明通道
img_unchanged = cv.imread('logo.png', cv.IMREAD_UNCHANGED)
▸ 图像本质:H×W×C 的 uint8 矩阵
2. 显示图像:cv.imshow()
cv.imshow(winname, img) 在 GUI 窗口显示图像。配合 cv.waitKey() 和 cv.destroyAllWindows() 控制显示时长。
cv.imshow('运动检测窗口', img_color)
key = cv.waitKey(0) # 等待按键
cv.destroyAllWindows() # 关闭所有窗口
💡 提示: 在 Jupyter 或远程环境中,可使用 matplotlib 显示(注意 BGR→RGB 转换)。
3. 保存图像:cv.imwrite()
cv.imwrite(filename, img) 将数组编码为图像文件。支持 PNG、JPEG、TIFF 等格式。可通过 cv.IMWRITE_JPEG_QUALITY 等参数控制质量。
# 保存为 PNG (无损)
cv.imwrite('output.png', img_color)
# 保存为 JPEG,质量 90
params = [cv.IMWRITE_JPEG_QUALITY, 90]
cv.imwrite('output.jpg', img_color, params)
▸ 常用保存格式及特点
4. 图像基本属性:shape & dtype
OpenCV 图像是 NumPy 数组,通过 .shape 和 .dtype 获取维度与数据类型。
| 属性 | 示例值 | 说明 |
|---|---|---|
img.shape | (480, 640, 3) | 高度、宽度、通道数 (灰度图无通道维度) |
img.dtype | uint8 | 每个像素值范围 0~255 |
img.size | 921600 | 总像素数 = H×W×C |
print("图像形状:", img.shape) # (480, 640, 3)
print("数据类型:", img.dtype) # uint8
print("像素总数:", img.size) # 921600
▸ 图像三要素:形状、数据类型、总像素
5. 综合示例:读取→属性→显示→保存
import cv2 as cv
# 读取
img = cv.imread('test.jpg', cv.IMREAD_COLOR)
if img is None:
print("图像读取失败,请检查路径")
else:
# 属性
print(f"shape: {img.shape}, dtype: {img.dtype}")
# 显示
cv.imshow('OpenCV 基础', img)
cv.waitKey(2000) # 显示2秒
# 保存
cv.imwrite('test_copy.png', img)
cv.destroyAllWindows()