"""Independent offline OpenCV tutorial lab: imread checks, Esc key logic, and NumPy BGR/RGB interop."""
import json
import platform
import tempfile
from pathlib import Path
import cv2 as cv
import numpy as np
def run_cases():
cases = []
# 1. Valid image read vs missing path returning None + grayscale read
with tempfile.TemporaryDirectory() as tmp:
img_path = Path(tmp) / "sample_scene.png"
missing_path = Path(tmp) / "does_not_exist.png"
canvas = np.zeros((64, 96, 3), dtype=np.uint8)
canvas[:, :] = (40, 80, 160) # BGR
cv.rectangle(canvas, (12, 10), (84, 54), (220, 180, 60), -1)
cv.circle(canvas, (48, 32), 14, (30, 210, 240), -1)
wrote = cv.imwrite(str(img_path), canvas)
loaded = cv.imread(str(img_path))
loaded_gray = cv.imread(str(img_path), cv.IMREAD_GRAYSCALE)
missing = cv.imread(str(missing_path))
ok1 = (
wrote
and loaded is not None
and loaded.shape == (64, 96, 3)
and loaded.dtype == np.uint8
and np.array_equal(loaded, canvas)
and loaded_gray is not None
and loaded_gray.shape == (64, 96)
and missing is None
)
cases.append(dict(
name="imread_missing_and_valid",
inputs=dict(width=96, height=64, channels=3),
prerequisites="本地合成 BGR PNG 文件与不存在路径",
action="使用 cv.imread 分别读取存在的彩色/灰度图像及不存在路径,核对返回形状、数据类型与 None 行为。",
expected=dict(
wrote=True,
bgr_shape=[64, 96, 3],
gray_shape=[64, 96],
missing_is_none=True,
lossless_equal=True,
),
actual=dict(
wrote=bool(wrote),
bgr_shape=list(loaded.shape) if loaded is not None else None,
gray_shape=list(loaded_gray.shape) if loaded_gray is not None else None,
missing_is_none=missing is None,
lossless_equal=bool(loaded is not None and np.array_equal(loaded, canvas)),
),
measurements=dict(
dtype=str(loaded.dtype),
center_bgr=loaded[32, 48].tolist(),
center_gray=int(loaded_gray[32, 48]),
file_bytes=img_path.stat().st_size,
),
passed=ok1,
))
# 2. Esc key ASCII dispatch logic (headless-safe verification of k == 27 branch)
def handle_key(key_code: int) -> str:
if key_code == 27:
return "destroy_all_windows"
return "keep_open"
esc_code = ord("\x1b")
res_esc = handle_key(esc_code)
res_other = handle_key(ord("a"))
ok2 = esc_code == 27 and res_esc == "destroy_all_windows" and res_other == "keep_open"
cases.append(dict(
name="esc_key_dispatch_logic",
inputs=dict(esc_char="\\x1b", other_char="a"),
prerequisites="无头模式下使用按键码分发函数模拟 cv.waitKey(0) 返回值判断",
action="验证 Esc 键 ASCII 码为 27 且触发关闭窗口分支,普通按键('a'=97)不触发关闭分支。",
expected=dict(esc_ascii=27, esc_action="destroy_all_windows", other_action="keep_open"),
actual=dict(esc_ascii=esc_code, esc_action=res_esc, other_action=res_other),
measurements=dict(a_ascii=ord("a")),
passed=ok2,
))
# 3. OpenCV + NumPy interop and BGR <-> RGB consistency
sample = np.array([[[10, 120, 230], [50, 100, 150]]], dtype=np.uint8)
rgb_cv = cv.cvtColor(sample, cv.COLOR_BGR2RGB)
rgb_np = sample[:, :, ::-1]
equal_rgb = bool(np.array_equal(rgb_cv, rgb_np))
ver_parts = tuple(int(x) for x in cv.__version__.split(".")[:2])
ok3 = equal_rgb and ver_parts >= (4, 0) and rgb_cv[0, 0].tolist() == [230, 120, 10]
cases.append(dict(
name="opencv_numpy_interop",
inputs=dict(bgr_pixel=[10, 120, 230]),
prerequisites="OpenCV 与 NumPy 共享底层 ndarray 缓冲区",
action="验证 cv.cvtColor(COLOR_BGR2RGB) 与 NumPy 通道反转切片输出一致,并读取 OpenCV 版本号。",
expected=dict(rgb_pixel=[230, 120, 10], cv_equals_numpy_flip=True, version_ge_4=True),
actual=dict(
rgb_pixel=rgb_cv[0, 0].tolist(),
cv_equals_numpy_flip=equal_rgb,
version_ge_4=ver_parts >= (4, 0),
),
measurements=dict(cv2_version=cv.__version__, numpy_version=np.__version__),
passed=ok3,
))
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 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-tutorial-lab/explore-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a596.zip