蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测像素修改、ROI 视图、通道拆分合并、四种几何变换及 5 联可视化对比图

PYTHONWindows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。explore-image-operator.py
explore-image-operator.py239 行
"""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)
本例需在 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。

入口文件:projects/opencv-image-operator-lab/explore-image-operator.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-image-operator.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCV

课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip

下载课程关联工程包:OpenCV

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a586.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习