第3章 OpenCV基础操作
读取图像 · 显示图像 · 保存图像 · 图像属性获取
cv2.imread / imshow / imwrite
3.1 读取图像
使用 cv2.imread() 将图像从磁盘加载为 NumPy 数组。支持彩色、灰度、原始格式。
import cv2
# 读取彩色图像 (默认 BGR)
img = cv2.imread('example.jpg')
# 读取灰度图像
gray = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
# 读取包含 alpha 通道的图像
unchange = cv2.imread('example.jpg', cv2.IMREAD_UNCHANGED)
3.2 显示图像
cv2.imshow() 创建窗口并显示图像,配合 waitKey() 和 destroyAllWindows() 控制显示时长。
cv2.imshow('显示窗口', img)
cv2.waitKey(0) # 等待按键
cv2.destroyAllWindows() # 关闭所有窗口
3.3 保存图像
cv2.imwrite() 将数组编码并写入磁盘,支持 PNG、JPEG 等格式。
success = cv2.imwrite('output.png', img)
if success:
print("图像保存成功")
3.4 图像属性获取
通过 NumPy 数组的 shape、dtype、size 获取尺寸、通道数、数据类型等信息。
| 属性 | 代码 | 说明 |
|---|---|---|
| 高度、宽度、通道数 | img.shape | 返回 (H, W, C) 元组 |
| 像素总数 | img.size | H × W × C |
| 数据类型 | img.dtype | 通常为 uint8 |
| 通道数 | img.shape[2] | 灰度图无此维度 |
import cv2
img = cv2.imread('scene.jpg')
h, w, c = img.shape
print(f"分辨率: {w} x {h}, 通道数: {c}")
print(f"数据类型: {img.dtype}, 总像素: {img.size}")
3.5 综合小例程
读取图像 → 显示属性 → 灰度转换 → 保存新图像。
import cv2
# 读取
color = cv2.imread('flower.jpg')
print('原始 shape:', color.shape)
# 转灰度
gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)
print('灰度 shape:', gray.shape)
# 保存
cv2.imwrite('flower_gray.png', gray)
# 显示
cv2.imshow('彩色', color)
cv2.imshow('灰度', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()