OpenCV 图像基本操作
精讲像素访问修改、ROI 切片视图特性、BGR 通道拆分合并以及缩放、旋转、平移与翻转四大几何变换,附常用方法对照表与 5 联实测对比图。
学完这一章,你能够
- 精讲像素访问修改、ROI 切片视图特性、BGR 通道拆分合并以及缩放、旋转、平移与翻转四大几何变换,附常用方法对照表与 5 联实测对比图。
常用操作速查与像素级读写
图像最核心的四类日常操作包括像素读写、ROI 局部切片、颜色通道分离合并以及缩放/旋转/平移/翻转几何变换。下方参考表同步汇总了这四类操作及后续章节衔接的算术、阈值与平滑入口,便于快速检索。
数字图像在内存中表现为二维或三维像素矩阵:灰度图每个位置存储单个强度值,彩色图存储三个通道值。在 Python OpenCV 中访问 `(x, y)` 处像素须按先行后列写成 `img[y, x]`(单通道值可用 `img[y, x, c]`,其中 `c=0` 为蓝 B、`1` 为绿 G、`2` 为红 R),直接赋值即可改写。本站实测 `240×320` 合成 BGR 图像:读取 `img[100, 150]` 得到 `[40, 120, 230]`,赋值为 `[255, 255, 255]` 后立即变为纯白。
ROI 感兴趣区域提取与修改
ROI(Region of Interest)用于将算力集中在图像的局部目标区域,通过 NumPy 切片 `roi = img[0:100, 0:100]` 即可截取左上角 `100×100` 区域。需要特别留意:NumPy 切片返回的是原数组视图(view)而非独立副本,执行 `roi[:, :] = [0, 255, 0]` 时原图对应区域会同步变为绿色(即使省略再次写回 `img[0:100, 0:100] = roi` 也已原位生效);若不想影响原图,应先调用 `.copy()`。
图像通道分离与合并
当需要对单个颜色分量做滤波、直方图调整或通道重排时,可用 `b, g, r = cv2.split(img)` 拆出三个 `(H, W)` 单通道矩阵,处理完毕再以 `cv2.merge([b, g, r])` 还原为多通道图像。本站实测拆出的三通道形状均为 `(240, 320)`,均值分别为 B=`84.45`、G=`109.91`、R=`107.41`,探针 `(100, 150)` 组合还原与原图逐像素相等,按 `[r, g, b]` 合并则得到 `[230, 120, 40]`。
几何变换:缩放、旋转、平移与翻转
几何变换改变像素的空间坐标排布:`cv2.resize(img, (200, 200))` 按指定 `(宽, 高)` 或缩放因子重采样(默认双线性插值);旋转需先以 `M = cv2.getRotationMatrix2D(center, 45, 1.0)` 构造绕中心点逆时针旋转 45° 的 `2×3` 仿射矩阵,再交给 `cv2.warpAffine(img, M, (w, h))` 执行重映射。本站实测缩放输出形状精确为 `(200, 200, 3)`,绕中心 `(160, 120)` 旋转 45° 后中心像素仍保持 `[40, 120, 230]`。
图像平移同样调用 `cv2.warpAffine()`,只需传入平移矩阵 `M = np.float32([[1, 0, tx], [0, 1, ty]])`(如 `tx=100, ty=50` 表示右移 100、下移 50 像素,越界空白默认填黑 `[0, 0, 0]`);翻转则直接用 `cv2.flip(img, flipCode)`,其中 `1` 水平翻转、`0` 垂直翻转、`-1` 双向翻转。本站实测平移后原 `(150, 100)` 像素精确落到 `(250, 150)` 且 `(10, 10)` 空白边界为 `[0, 0, 0]`,三种翻转的镜像坐标全部精确匹配。下方为本站实测生成的 5 联变换对比图。

OpenCV 图像基本与关联操作速查表
| 操作类别 | 常用接口 | 功能与实测要点 |
|---|---|---|
| 访问像素值 | `image[y, x]` / `image[y, x, c]` | 按先行后列读取或修改单点像素,彩色图默认通道序为 B/G/R。 |
| 图像 ROI | `image[y1:y2, x1:x2]` | 切片截取矩形子区域;返回 NumPy 视图,原位修改同步影响原图。 |
| 通道分离与合并 | `cv2.split()` / `cv2.merge()` | 拆分三通道为独立二维矩阵,或按目标顺序无损合并。 |
| 图像缩放 | `cv2.resize(img, (w, h))` | 按目标宽高或比例因子重采样,注意参数顺序为 `(width, height)`。 |
| 图像旋转 | `cv2.getRotationMatrix2D()` + `cv2.warpAffine()` | 生成绕指定中心逆时针旋转的 2×3 仿射矩阵并重映射像素。 |
| 图像平移 | `cv2.warpAffine(img, M, (w, h))` | 使用 `[[1,0,tx],[0,1,ty]]` 平移图像,越界默认填充黑色。 |
| 图像翻转 | `cv2.flip(img, flipCode)` | `1` 水平翻转、`0` 垂直翻转、`-1` 水平垂直双向翻转。 |
| 图像加法 | `cv2.add(img1, img2)` | 对应像素饱和相加,超过 255 自动截断为 255。 |
| 图像减法 | `cv2.subtract(img1, img2)` | 对应像素饱和相减,小于 0 自动截断为 0。 |
| 图像混合 | `cv2.addWeighted(i1, a, i2, b, g)` | 按权重 `a`/`b` 与偏置 `g` 做线性加权融合。 |
| 阈值处理 | `cv2.threshold()` | 按阈值分割前景与背景,输出二值或截断图像。 |
| 平滑处理 | `cv2.blur()` / `cv2.GaussianBlur()` | 通过均值或高斯核抑制噪声并平滑图像细节。 |
实测像素修改、ROI 视图、通道拆分合并、四种几何变换及 5 联可视化对比图
"""Independent offline OpenCV image-operator lab: pixel/ROI, split/merge, resize/rotate/translate/flip & visual chart."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import cv2
import numpy as np
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def build_base_image() -> np.ndarray:
img = np.zeros((240, 320, 3), dtype=np.uint8)
# Soft gradient background
xs = np.linspace(30, 140, 320, dtype=np.uint8)
ys = np.linspace(40, 160, 240, dtype=np.uint8)
img[:, :, 0] = xs[None, :]
img[:, :, 1] = ys[:, None]
img[:, :, 2] = 90
# Distinct asymmetric geometric landmarks for rotation/translation/flip verification
cv2.rectangle(img, (110, 50), (210, 150), (40, 120, 230), -1)
cv2.circle(img, (255, 85), 32, (230, 210, 40), -1)
cv2.putText(img, "ROI", (18, 56), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
return img
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
base = build_base_image()
# 1. Pixel access/modification & ROI slicing view semantics
img_px = base.copy()
before_px = img_px[100, 150].tolist()
img_px[100, 150] = [255, 255, 255]
after_px = img_px[100, 150].tolist()
img_roi = base.copy()
roi = img_roi[0:100, 0:100]
roi[:, :] = [0, 255, 0]
# Because NumPy slicing returns a view, img_roi[0:100, 0:100] is already updated in-place
view_mutated_in_place = img_roi[10, 10].tolist() == [0, 255, 0]
img_roi[0:100, 0:100] = roi
ok1 = (
before_px == [40, 120, 230]
and after_px == [255, 255, 255]
and roi.shape == (100, 100, 3)
and view_mutated_in_place
)
cases.append(dict(
name="pixel_and_roi_ops",
inputs=dict(pixel_yx=[100, 150], roi_slice="0:100, 0:100"),
prerequisites="240x320 合成 BGR 图像((150,100) 位于橙红色矩形内)",
action="读取并改写 img[100, 150] 为白色,提取左上角 100x100 ROI 赋为绿色并核对 NumPy 切片视图原位生效特性。",
expected=dict(
before_bgr=[40, 120, 230],
after_bgr=[255, 255, 255],
roi_shape=[100, 100, 3],
slice_is_view=True,
),
actual=dict(
before_bgr=before_px,
after_bgr=after_px,
roi_shape=list(roi.shape),
slice_is_view=view_mutated_in_place,
),
measurements=dict(roi_corner_bgr=img_roi[0, 0].tolist()),
passed=ok1,
))
# 2. Channel split and merge
b, g, r = cv2.split(base)
merged = cv2.merge([b, g, r])
swapped_rgb = cv2.merge([r, g, b])
ok2 = (
b.shape == g.shape == r.shape == (240, 320)
and [int(b[100, 150]), int(g[100, 150]), int(r[100, 150])] == [40, 120, 230]
and np.array_equal(merged, base)
and swapped_rgb[100, 150].tolist() == [230, 120, 40]
)
cases.append(dict(
name="channel_split_merge",
inputs=dict(probe_yx=[100, 150]),
prerequisites="三通道 BGR 图像",
action="执行 cv2.split 分离 B/G/R 单通道并核对探针像素值,再以 cv2.merge 精确重构原图及通道重排图。",
expected=dict(
channel_shape=[240, 320],
probe_bgr=[40, 120, 230],
lossless_merge=True,
swapped_rgb=[230, 120, 40],
),
actual=dict(
channel_shape=list(b.shape),
probe_bgr=[int(b[100, 150]), int(g[100, 150]), int(r[100, 150])],
lossless_merge=bool(np.array_equal(merged, base)),
swapped_rgb=swapped_rgb[100, 150].tolist(),
),
measurements=dict(
b_mean=round(float(b.mean()), 2),
g_mean=round(float(g.mean()), 2),
r_mean=round(float(r.mean()), 2),
),
passed=ok2,
))
# 3. Resize, rotate, translate, flip
h, w = base.shape[:2]
resized = cv2.resize(base, (200, 200))
center = (w // 2, h // 2)
m_rot = cv2.getRotationMatrix2D(center, 45, 1.0)
rotated = cv2.warpAffine(base, m_rot, (w, h))
m_trans = np.float32([[1, 0, 100], [0, 1, 50]])
translated = cv2.warpAffine(base, m_trans, (w, h))
flipped_h = cv2.flip(base, 1)
flipped_v = cv2.flip(base, 0)
flipped_b = cv2.flip(base, -1)
# Check exact pixel coordinate mapping for translation & horizontal flip
trans_match = translated[150, 250].tolist() == base[100, 150].tolist()
trans_border_black = translated[10, 10].tolist() == [0, 0, 0]
flip_h_match = flipped_h[100, w - 1 - 150].tolist() == base[100, 150].tolist()
flip_v_match = flipped_v[h - 1 - 100, 150].tolist() == base[100, 150].tolist()
flip_b_match = flipped_b[h - 1 - 100, w - 1 - 150].tolist() == base[100, 150].tolist()
ok3 = (
resized.shape == (200, 200, 3)
and rotated.shape == (240, 320, 3)
and trans_match
and trans_border_black
and flip_h_match
and flip_v_match
and flip_b_match
)
cases.append(dict(
name="geometric_transforms",
inputs=dict(resize_wh=[200, 200], rotate_deg=45, translate_xy=[100, 50]),
prerequisites="240x320 非对称几何地标 BGR 图像",
action="执行 200x200 缩放、绕中心逆时针旋转 45 度、向右 100/向下 50 像素平移以及水平/垂直/双向翻转,核对坐标精确映射。",
expected=dict(
resized_shape=[200, 200, 3],
translation_pixel_matched=True,
translation_border_zero=True,
all_three_flips_exact=True,
),
actual=dict(
resized_shape=list(resized.shape),
translation_pixel_matched=trans_match,
translation_border_zero=trans_border_black,
all_three_flips_exact=(flip_h_match and flip_v_match and flip_b_match),
),
measurements=dict(
rot_center_bgr=rotated[center[1], center[0]].tolist(),
orig_center_bgr=base[center[1], center[0]].tolist(),
),
passed=ok3,
))
# 4. Extra operations listed in chapter summary table (add/subtract/addWeighted/threshold/blur/GaussianBlur)
p1 = np.full((40, 40), 190, dtype=np.uint8)
p2 = np.full((40, 40), 100, dtype=np.uint8)
add_v = int(cv2.add(p1, p2)[0, 0])
sub_v = int(cv2.subtract(p2, p1)[0, 0])
w_v = int(cv2.addWeighted(p1, 0.6, p2, 0.4, 0)[0, 0])
gray = cv2.cvtColor(base, cv2.COLOR_BGR2GRAY)
_, th = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)
b_box = cv2.blur(gray, (5, 5))
b_gau = cv2.GaussianBlur(gray, (5, 5), 0)
ok4 = add_v == 255 and sub_v == 0 and w_v == 154 and th.shape == (240, 320) and b_box.shape == b_gau.shape == (240, 320)
cases.append(dict(
name="summary_table_extra_ops",
inputs=dict(p1=190, p2=100, alpha=0.6, beta=0.4),
prerequisites="核对本章常用方法总表中后 5 项关联函数",
action="验证 cv2.add 饱和截断 255、cv2.subtract 下界截断 0、cv2.addWeighted 线性加权 154、cv2.threshold 二值化与均值/高斯平滑。",
expected=dict(add_val=255, sub_val=0, weighted_val=154, smooth_ok=True),
actual=dict(add_val=add_v, sub_val=sub_v, weighted_val=w_v, smooth_ok=(b_box.shape == b_gau.shape == (240, 320))),
measurements=dict(thresh_white_pixels=int(np.count_nonzero(th))),
passed=ok4,
))
# 5. Crisp matplotlib figure showing ROI & geometric transforms
mpl_ver = None
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
fig_dir.mkdir(parents=True, exist_ok=True)
panels = [
("原图 (320×240)", cv2.cvtColor(base, cv2.COLOR_BGR2RGB)),
("ROI 替换 (左上 100×100)", cv2.cvtColor(img_roi, cv2.COLOR_BGR2RGB)),
("旋转 45° (warpAffine)", cv2.cvtColor(rotated, cv2.COLOR_BGR2RGB)),
("平移 (+100, +50)", cv2.cvtColor(translated, cv2.COLOR_BGR2RGB)),
("水平翻转 (flipCode=1)", cv2.cvtColor(flipped_h, cv2.COLOR_BGR2RGB)),
]
fig, axes = plt.subplots(1, 5, figsize=(13.0, 2.9), dpi=140)
for ax, (ttl, im_rgb) in zip(axes, panels):
ax.imshow(im_rgb)
ax.set_title(ttl, fontsize=9.5)
ax.axis("off")
fig.suptitle("OpenCV 图像 ROI 与几何变换实测对比", fontsize=11.5, y=0.98)
fig.tight_layout()
out_png = fig_dir / "image-operator-transforms.png"
fig.savefig(out_png)
plt.close(fig)
figures["image-operator-transforms.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="operator_transforms_figure",
inputs=dict(panels=5),
prerequisites="原图、ROI 替换图与旋转/平移/翻转实测结果",
action="生成 5 联实测对比图 image-operator-transforms.png。",
expected=dict(panel_count=5, output_shape=[240, 320, 3]),
actual=dict(panel_count=5, output_shape=list(rotated.shape)),
measurements=dict(figure_generated="image-operator-transforms.png" in figures),
passed=True,
))
payload = dict(version=platform.python_version(), system=platform.system(), cases=cases)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
- 核对 img[100,150] 读写、ROI 切片视图原位生效、split/merge 还原、缩放 (200,200,3)/旋转 45°/平移 (+100,+50)/三向翻转与 PNG 对比图。
所需环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。
当前源码 SHA256:0effd404126d8263bff12785602e517cd97a89ad8c0e283c80cb007f2b333ba4
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。
ZIP SHA256:d94d1ff871a111491d6acfcf861bb4b0b5940b22e6712cad389ce76c20cd0115
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
执行 `roi = img[0:100, 0:100]` 后修改 `roi[:, :] = [0, 255, 0]`,如果不写 `img[0:100, 0:100] = roi`,原图会变化吗?如何避免误改原图?
展开参考解答
原图会立即一起变化,因为 NumPy 基本切片返回的是共享同一块内存缓冲区的视图(view)。如果希望独立编辑子区域而不破坏原图,应使用 `roi = img[0:100, 0:100].copy()` 显式深拷贝。