C++ OpenCV 基础操作
系统梳理 C++ OpenCV 的图像读写与属性查询、cv::Mat 创建/ROI/克隆内存语义、几何变换(缩放、旋转、平移、翻转、仿射与透视)及颜色空间与通道拆分合并,并基于 OpenCV 5.1.0 核心绑定给出离线实测结果。
学完这一章,你能够
- 系统梳理 C++ OpenCV 的图像读写与属性查询、cv::Mat 创建/ROI/克隆内存语义、几何变换(缩放、旋转、平移、翻转、仿射与透视)及颜色空间与通道拆分合并,并基于 OpenCV 5.1.0 核心绑定给出离线实测结果。
图像读写、显示与基本属性查询
在 C++ OpenCV(头文件 `<opencv2/opencv.hpp>`)中,图像处理管线通常从读图、判空、展示与写盘起步:`cv::imread(path, flag)` 按 `cv::IMREAD_COLOR`(默认三通道 BGR)或 `cv::IMREAD_GRAYSCALE` 加载图像为 `cv::Mat`,加载后必须用 `image.empty()` 检查路径有效性;桌面调试阶段使用 `cv::namedWindow`、`cv::imshow`、`cv::waitKey(0)` 与 `cv::destroyAllWindows()` 完成窗口显示与按键退出;处理结果通过 `cv::imwrite(outPath, image)` 返回布尔值确认写盘成功。本站离线实测经 `imwrite`/`imread` 无损 PNG 往返写入 `480×640×3` 图像,`saved_ok` 为 `True` 且灰度模式读取为二维单通道矩阵。
图像的三个基础属性分别是尺寸、通道数与像素值:在 C++ 中通过 `image.rows` 获取高度、`image.cols` 获取宽度、`image.channels()` 获取通道数;按行优先坐标 `(y, x)` 访问三通道 8 位无符号图像像素时使用模板方法 `image.at<cv::Vec3b>(y, x)`(注意第一个下标是行号 `y`,第二个是列号 `x`,且默认通道顺序为 `B、G、R`)。本站实测加载图像精确测得 `rows=480`、`cols=640`、`channels=3`。
cv::Mat 创建、初始化、ROI 与像素操作
`cv::Mat` 支持按指定高宽、数据类型和初值直接构造图像,例如 `cv::Mat newImage(480, 640, CV_8UC3, cv::Scalar(0, 0, 255))` 会生成 `640×480` 的纯红 BGR 画布,随后可调用 `image.setTo(cv::Scalar(255, 255, 255))` 批量重置为纯白。裁剪感兴趣区域 `cv::Mat cropped = image(cv::Rect(100, 100, 200, 200))` 仅创建共享像素缓冲区的矩阵头(零拷贝),而 `cv::Mat copied = image.clone()` 会分配独立内存;本站实测 `200×200×3` ROI 切片与原图共享内存(`roi_shares_mem=True`),而对深拷贝画圆后原图 `(100, 150)` 像素仍保持 `[40, 120, 200]` 不受影响。
逐像素处理可通过外层 `y`(`0..rows-1`)、内层 `x`(`0..cols-1`)的双重循环获取引用 `cv::Vec3b& pixel = image.at<cv::Vec3b>(y, x)`,再分别改写 `pixel[0]`(蓝)、`pixel[1]`(绿)、`pixel[2]`(红)或直接赋值为 `cv::Vec3b(255, 0, 0)`。本站实测将 `(100, 100)` 像素由 `[40, 120, 200]` 修改为纯蓝 `[255, 0, 0]` 后读回值完全一致。
几何变换:缩放、旋转、平移、翻转、仿射与透视
基础几何变换覆盖缩放、旋转、平移与翻转:`cv::resize(src, dst, cv::Size(w, h))` 改变分辨率;`cv::getRotationMatrix2D(center, angle, scale)` 生成 `2×3` 旋转矩阵并交给 `cv::warpAffine` 执行旋转;手动构造 `2×3` 浮点矩阵 `[1, 0, tx; 0, 1, ty]` 配合 `cv::warpAffine` 实现平移;`cv::flip(src, dst, flipCode)` 在 `1` 时水平镜像、`0` 时垂直翻转。本站实测将 `200×300` 图像缩放到 `[400, 400, 3]`,水平/垂直翻转精确对调标记块像素,平移 `(+30, +20)` 命中新坐标 `(45, 65)`,45° 旋转矩阵首元素为 `0.7071` 且输出尺寸保持 `[200, 300, 3]`。
更一般的二维空间映射分为仿射变换与透视变换:仿射变换保留直线平行性,由三对不共线点调用 `cv::getAffineTransform(srcPoints, dstPoints)` 求 `2×3` 矩阵再经 `cv::warpAffine` 映射;透视变换由四对点调用 `cv::getPerspectiveTransform` 求 `3×3` 单应性矩阵再经 `cv::warpPerspective` 矫正投影畸变。本站实测 3 点仿射将原点精确映射到 `[10.0, 20.0]`,4 点透视将绿色梯形拉正为 `200×200` 矩形后中心像素为 `[0, 200, 100]` 且绿色覆盖率达 `>= 95%`。
颜色空间转换与通道分离合并
常见颜色空间包括三通道的 RGB(OpenCV 内存默认按 BGR 排列)、单通道表示亮度的灰度空间(Gray)以及由色调(Hue)、饱和度(Saturation)和明度(Value)构成的 HSV 空间。C++ 中统一通过 `cv::cvtColor(src, dst, code)` 转换,如 `cv::COLOR_BGR2GRAY` 与 `cv::COLOR_BGR2HSV`。本站实测纯蓝、纯绿、纯红三原色经 `COLOR_BGR2GRAY` 映射为 `[29, 150, 76]`,经 `COLOR_BGR2HSV` 分别对应 `[120, 255, 255]`、`[60, 255, 255]` 与 `[0, 255, 255]`。
需要单独处理某一颜色通道时,使用 `cv::split(image, channels)` 将多通道 `cv::Mat` 拆分为 `std::vector<cv::Mat>`,处理完毕再用 `cv::merge(channels, mergedImage)` 重新拼接。本站实测将三通道条带拆分出蓝色分量 `[255, 0, 0]` 后重新合并,与原图逐字节相等(`merge_exact_equal=True`)。
离线核验 OpenCV 基础读写、像素与 ROI/克隆语义、几何变换及颜色空间通道操作
展开查看收起
"""Offline verification lab for OpenCV Chapter 23: C++ OpenCV basic operations."""
import json
import tempfile
from pathlib import Path
import cv2
import numpy as np
def case_mat_io_and_pixel_ops():
# Simulate cv::Mat newImage(480, 640, CV_8UC3, cv::Scalar(0, 0, 255))
img = np.full((480, 640, 3), (0, 0, 255), dtype=np.uint8)
red_pixel = img[0, 0].tolist()
# Simulate setTo(cv::Scalar(255, 255, 255))
img[:, :] = (255, 255, 255)
white_pixel = img[10, 10].tolist()
# Draw deterministic content and verify imwrite / imread round-trip
cv2.rectangle(img, (80, 80), (320, 320), (40, 120, 200), -1)
with tempfile.TemporaryDirectory() as tmp:
out_path = Path(tmp) / "saved_image.png"
saved_ok = bool(cv2.imwrite(str(out_path), img))
loaded_color = cv2.imread(str(out_path), cv2.IMREAD_COLOR)
loaded_gray = cv2.imread(str(out_path), cv2.IMREAD_GRAYSCALE)
rows, cols, channels = loaded_color.shape
before_px = loaded_color[100, 100].tolist()
loaded_color[100, 100] = (255, 0, 0)
after_px = loaded_color[100, 100].tolist()
# ROI slice shares memory (like cv::Mat cropped = image(roi))
roi = loaded_color[100:300, 100:300]
roi_shape = list(roi.shape)
roi_shares_mem = bool(np.shares_memory(loaded_color, roi))
# clone() allocates independent memory
cloned = loaded_color.copy()
cv2.circle(cloned, (100, 100), 50, (0, 255, 0), 2)
clone_independent = bool(
not np.shares_memory(loaded_color, cloned)
and not np.array_equal(loaded_color, cloned)
and loaded_color[100, 150].tolist() == [40, 120, 200]
)
actual = dict(
red_pixel=red_pixel,
white_pixel=white_pixel,
saved_ok=saved_ok,
rows=rows,
cols=cols,
channels=channels,
gray_ndim=int(loaded_gray.ndim),
before_px=before_px,
after_px=after_px,
roi_shape=roi_shape,
roi_shares_mem=roi_shares_mem,
clone_independent=clone_independent,
)
expected = dict(
red_pixel=[0, 0, 255],
white_pixel=[255, 255, 255],
saved_ok=True,
rows=480,
cols=640,
channels=3,
gray_ndim=2,
before_px=[40, 120, 200],
after_px=[255, 0, 0],
roi_shape=[200, 200, 3],
roi_shares_mem=True,
clone_independent=True,
)
return dict(name="mat_io_and_pixel_ops", passed=actual == expected, expected=expected, actual=actual)
def case_geometric_resize_flip_rotate():
img = np.zeros((200, 300, 3), dtype=np.uint8)
img[20:40, 30:50] = (10, 180, 240)
resized = cv2.resize(img, (400, 400))
flipped_h = cv2.flip(img, 1)
flipped_v = cv2.flip(img, 0)
# Check exact corner swap under horizontal/vertical flip
h_swapped = flipped_h[25, 300 - 1 - 35].tolist()
v_swapped = flipped_v[200 - 1 - 25, 35].tolist()
# Translation by (+30, +20)
trans_m = np.array([[1.0, 0.0, 30.0], [0.0, 1.0, 20.0]], dtype=np.float64)
translated = cv2.warpAffine(img, trans_m, (img.shape[1], img.shape[0]))
trans_hit = translated[45, 65].tolist()
# Rotation by 45 degrees around center
center = (img.shape[1] / 2.0, img.shape[0] / 2.0)
rot_m = cv2.getRotationMatrix2D(center, 45.0, 1.0)
rotated = cv2.warpAffine(img, rot_m, (img.shape[1], img.shape[0]))
actual = dict(
resized_shape=list(resized.shape),
h_swapped=h_swapped,
v_swapped=v_swapped,
trans_hit=trans_hit,
rot_matrix_shape=list(rot_m.shape),
rot_cos45=round(float(rot_m[0, 0]), 4),
rotated_shape=list(rotated.shape),
rotated_nonzero=bool(int(np.count_nonzero(rotated)) > 0),
)
expected = dict(
resized_shape=[400, 400, 3],
h_swapped=[10, 180, 240],
v_swapped=[10, 180, 240],
trans_hit=[10, 180, 240],
rot_matrix_shape=[2, 3],
rot_cos45=0.7071,
rotated_shape=[200, 300, 3],
rotated_nonzero=True,
)
return dict(name="geometric_resize_flip_rotate", passed=actual == expected, expected=expected, actual=actual)
def case_affine_and_perspective_warp():
img = np.zeros((200, 200, 3), dtype=np.uint8)
pts_poly = np.array([[50, 40], [150, 40], [180, 160], [20, 160]], dtype=np.int32)
cv2.fillConvexPoly(img, pts_poly, (0, 200, 100))
# 3-point affine transform
src3 = np.float32([[0, 0], [100, 0], [0, 100]])
dst3 = np.float32([[10, 20], [110, 20], [20, 120]])
aff_m = cv2.getAffineTransform(src3, dst3)
aff_img = cv2.warpAffine(img, aff_m, (200, 200))
mapped_origin = [round(float(v), 2) for v in (aff_m @ np.array([0.0, 0.0, 1.0]))]
# 4-point perspective transform (rectify trapezoid to full 200x200 square)
src4 = np.float32([[50, 40], [150, 40], [180, 160], [20, 160]])
dst4 = np.float32([[0, 0], [199, 0], [199, 199], [0, 199]])
persp_m = cv2.getPerspectiveTransform(src4, dst4)
persp_img = cv2.warpPerspective(img, persp_m, (200, 200))
center_px = persp_img[100, 100].tolist()
green_coverage = round(float(np.mean(persp_img[:, :, 1] == 200)), 2)
actual = dict(
affine_shape=list(aff_m.shape),
mapped_origin=mapped_origin,
affine_nonzero=bool(int(np.count_nonzero(aff_img)) > 0),
persp_shape=list(persp_m.shape),
center_px=center_px,
rectified_mostly_green=bool(green_coverage >= 0.95),
)
expected = dict(
affine_shape=[2, 3],
mapped_origin=[10.0, 20.0],
affine_nonzero=True,
persp_shape=[3, 3],
center_px=[0, 200, 100],
rectified_mostly_green=True,
)
return dict(name="affine_and_perspective_warp", passed=actual == expected, expected=expected, actual=actual)
def case_colorspace_and_channel_split_merge():
# 1x3 BGR strip: Blue (255,0,0), Green (0,255,0), Red (0,0,255)
bgr = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], dtype=np.uint8)
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
b, g, r = cv2.split(bgr)
merged = cv2.merge([b, g, r])
actual = dict(
gray_bgr_primaries=gray[0].tolist(),
hsv_blue=hsv[0, 0].tolist(),
hsv_green=hsv[0, 1].tolist(),
hsv_red=hsv[0, 2].tolist(),
split_channel_count=3,
b_channel=b[0].tolist(),
merge_exact_equal=bool(np.array_equal(bgr, merged)),
)
expected = dict(
gray_bgr_primaries=[29, 150, 76],
hsv_blue=[120, 255, 255],
hsv_green=[60, 255, 255],
hsv_red=[0, 255, 255],
split_channel_count=3,
b_channel=[255, 0, 0],
merge_exact_equal=True,
)
return dict(name="colorspace_and_channel_split_merge", passed=actual == expected, expected=expected, actual=actual)
def main():
cases = [
case_mat_io_and_pixel_ops(),
case_geometric_resize_flip_rotate(),
case_affine_and_perspective_warp(),
case_colorspace_and_channel_split_merge(),
]
print(json.dumps({"cases": cases, "figures": {}}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`image(rect)` 返回共享底层像素缓冲区的矩阵头,修改 ROI 会同步改变原图对应区域;`image.clone()` 会分配独立内存并拷贝像素,修改副本不会影响原图。