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

离线核验 OpenCV 基础读写、像素与 ROI/克隆语义、几何变换及颜色空间通道操作

PYTHONWindows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。explore-cpp-opencv-basic.py
explore-cpp-opencv-basic.py202 行
"""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()
本例需在 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-cpp-opencv-basic-lab/explore-cpp-opencv-basic.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-opencv-basic.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章) · 含当前章节或实例 · mbskycom202612a569.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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