蓝色天空网mbsky.com · 知识 · 实践 · 创造OpenCV · 本地阅读预览
教程 / AI / 智能开发 / OpenCV

OpenCV 图像处理基础

全景导览 OpenCV 图像数组表示、读写、像素/ROI/通道、几何与颜色空间变换、算术/阈值/平滑、边缘/形态学/轮廓以及离线视频读写主线。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

图像的数组表示与读写基础

OpenCV Python 接口以 NumPy 多维数组表示图像:彩色图默认采用三通道 BGR 排列(常与 RGB 对照理解),灰度图为单通道二维数组;通过 `img.shape` 可读取 `(高度, 宽度[, 通道数])`,常见数据类型为 `0~255` 范围的 `uint8`,高精度梯度或归一化运算则常用 `float32`。

基础 I/O 围绕三个函数展开:`cv2.imread()` 读取文件并返回 NumPy 数组(路径无效或文件缺失时返回 `None`);桌面环境下由 `cv2.imshow()`、`cv2.waitKey(0)` 与 `cv2.destroyAllWindows()` 完成预览关闭;`cv2.imwrite()` 将处理结果持久化到指定路径。本站实测 `200×240×3` 合成 BGR 图像无损保存并重载,归一化 `float32` 最大值 `0.7843`,缺失路径返回 `None`。

像素、ROI、通道、几何变换与颜色空间

基础像素级与几何操作包含四块:用 `image[y, x]` 读取或修改 BGR 像素值;用切片 `image[y1:y2, x1:x2]` 提取并修改感兴趣区域(ROI);用 `cv2.split()` 与 `cv2.merge()` 拆分和重组通道;以及结合 `cv2.resize()`、`cv2.getRotationMatrix2D()` + `cv2.warpAffine()`(旋转与平移)和 `cv2.flip()`(`0` 垂直、`1` 水平、`-1` 双向)完成几何变换。本站实测将 `(100, 100)` 像素原值 `[200, 120, 50]` 改写并把 `50:150, 50:150` ROI 设为纯绿 `[0, 255, 0]`,`split`/`merge` 还原完全一致,三向翻转二次操作均精确可逆。

`cv2.cvtColor()` 支持在多种颜色空间间切换:常用 `COLOR_BGR2GRAY` 转为单通道灰度图(注意 OpenCV 读入默认通道序为 BGR,即便口头上常称彩色图为 RGB,转换码仍应选用 `BGR2*`)、`COLOR_BGR2HSV` 用于色相/饱和度分割、`COLOR_BGR2YUV` 用于亮度色度分离。同时可配合 `cv2.resize(img, (width, height))` 调整分辨率(参数顺序为先宽后高)并用 `img[y1:y2, x1:x2]` 裁剪局部区域。本站实测 `(100, 100)` 像素经转换后灰度值 `108`、HSV `[106, 191, 200]`、YUV `[108, 173, 77]`,裁剪与缩放输出均为 `(100, 120, 3)`。

算术运算、阈值分割与图像平滑概览

算术与阈值处理是分割前的核心步骤:`cv2.add()` 与 `cv2.subtract()` 执行饱和加减,避免 `uint8` 溢出回绕;`cv2.addWeighted(image1, alpha, image2, beta, gamma)` 按权重 `alpha`/`beta` 与偏置 `gamma` 线性混合图像。阈值化支持固定阈值 `cv2.threshold(src, thresh, maxval, cv2.THRESH_BINARY)`、局部自适应 `cv2.adaptiveThreshold()` 以及无需手调阈值的 Otsu 自动二值化(`cv2.THRESH_BINARY + cv2.THRESH_OTSU`)。本站实测 `200 + 100` 饱和得 `255`、`100 - 200` 截断得 `0`、`0.7×200 + 0.3×100` 混合得 `170`,双峰 50/210 方块图 Otsu 自动阈值 `50.0` 与固定阈值 `127` 二值结果一致。

图像平滑用于抑制随机噪声与高频干扰,OpenCV 提供四种代表滤波:均匀核均值滤波 `cv2.blur(img, (5, 5))`、按中心加权的高斯滤波 `cv2.GaussianBlur(img, (5, 5), 0)`、擅长滤除椒盐噪点的非线性中值滤波 `cv2.medianBlur(img, 5)`,以及兼顾空间邻近与色差保边的双边滤波 `cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)`。本站实测在阶跃边界处,双边滤波保留阶跃梯度 `138`,明显高于高斯滤波的 `60`。

边缘检测、形态学、轮廓提取与视频读取

边缘检测用于定位亮度突变区域:`cv2.Canny(img, 100, 200)` 经梯度计算、非极大值抑制与双阈值连接输出白边黑底二值图;`cv2.Sobel(image, cv2.CV_64F, ...)` 分别计算水平与垂直一阶偏导;`cv2.Laplacian(image, cv2.CV_64F)` 提取二阶微分响应(使用 `CV_64F` 避免负梯度截断)。

二值形态学借助 `cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))` 构造结构元:`cv2.erode()` 收缩白色前景,`cv2.dilate()` 扩张前景,`cv2.morphologyEx()` 的开运算(`MORPH_OPEN`,先腐蚀后膨胀)用于清除孤立小噪点,闭运算(`MORPH_CLOSE`,先膨胀后腐蚀)用于填补前景内部小孔洞。随后结合灰度化、二值化、`cv2.findContours(threshold_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)` 与 `cv2.drawContours()` 提取并绘制物体外轮廓。本站实测 `120×160` 双图形二值图:原白色前景 `5837` 像素经腐蚀缩至 `4965`、膨胀增至 `6785`,开运算精准抹除 `(6, 6)` 噪点、闭运算填满 `(56, 43)` 孔洞,Canny 检出 `410` 边缘像素,`findContours` 精确检出 `2` 个外部轮廓。

视频本质上是按帧率连续排列的图像序列,通过 `cv2.VideoCapture()` 打开视频文件或摄像头,在 `while cap.isOpened():` 循环中调用 `ret, frame = cap.read()` 逐帧处理(桌面交互常用 `cv2.waitKey(1) & 0xFF == ord('q')` 退出),结束后必须调用 `cap.release()` 释放句柄。本站离线写入 4 帧 `80×60` MJPG AVI 测试视频并用 `cv2.VideoCapture` 逐帧回读,确认完整读取全部 `4` 帧且每帧形状为 `(60, 80, 3)`。

全链路实测图像属性/读写/ROI/颜色空间/阈值/滤波/边缘/形态学/轮廓与离线视频读取

python · 阅读源码
"""Independent offline OpenCV image-basic lab: full pipeline from attributes/IO/ROI to edges, morphology, contours & video."""
import json
import platform
import tempfile
from pathlib import Path

import cv2
import numpy as np


def run_cases():
    cases = []

    # 1. Image attributes, IO, pixel access, ROI, and channel split/merge
    img = np.zeros((200, 240, 3), dtype=np.uint8)
    img[:, :] = (40, 90, 180)
    cv2.rectangle(img, (20, 20), (180, 160), (200, 120, 50), -1)
    img_f32 = img.astype(np.float32) / 255.0

    with tempfile.TemporaryDirectory() as tmp:
        p_ok = Path(tmp) / "output_image.png"
        cv2.imwrite(str(p_ok), img)
        reloaded = cv2.imread(str(p_ok))
        missing = cv2.imread(str(Path(tmp) / "missing.jpg"))

    work = reloaded.copy()
    orig_px = work[100, 100].tolist()
    work[100, 100] = [255, 255, 255]
    work[50:150, 50:150] = [0, 255, 0]
    b, g, r = cv2.split(work)
    merged = cv2.merge([b, g, r])

    ok1 = (
        reloaded.shape == (200, 240, 3)
        and reloaded.dtype == np.uint8
        and img_f32.dtype == np.float32
        and missing is None
        and orig_px == [200, 120, 50]
        and work[100, 100].tolist() == [0, 255, 0]
        and np.array_equal(work, merged)
    )
    cases.append(dict(
        name="image_attrs_io_pixel_roi_channels",
        inputs=dict(shape=[200, 240, 3], roi=[50, 150, 50, 150]),
        prerequisites="200x240 合成 BGR uint8 图像及对应 float32 归一化副本",
        action="验证 shape/dtype、imread/imwrite 读写与缺失返回 None、像素修改、ROI 赋绿及 split/merge 无损还原。",
        expected=dict(
            shape=[200, 240, 3],
            missing_is_none=True,
            orig_pixel=[200, 120, 50],
            roi_green=[0, 255, 0],
            merge_equal=True,
        ),
        actual=dict(
            shape=list(reloaded.shape),
            missing_is_none=(missing is None),
            orig_pixel=orig_px,
            roi_green=work[100, 100].tolist(),
            merge_equal=bool(np.array_equal(work, merged)),
        ),
        measurements=dict(
            uint8_dtype=str(reloaded.dtype),
            float32_max=round(float(img_f32.max()), 4),
            channel_shape=list(b.shape),
        ),
        passed=ok1,
    ))

    # 2. Geometry transforms & color space conversions (GRAY, HSV, YUV)
    resized = cv2.resize(img, (120, 100))
    cropped = img[20:120, 30:150]
    h, w = img.shape[:2]
    m_rot = cv2.getRotationMatrix2D((w // 2, h // 2), 30, 1.0)
    rotated = cv2.warpAffine(img, m_rot, (w, h))
    m_trans = np.float32([[1, 0, 25], [0, 1, 15]])
    translated = cv2.warpAffine(img, m_trans, (w, h))
    flip_v = cv2.flip(img, 0)
    flip_h = cv2.flip(img, 1)
    flip_both = cv2.flip(img, -1)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)

    ok2 = (
        resized.shape == (100, 120, 3)
        and cropped.shape == (100, 120, 3)
        and rotated.shape == translated.shape == (200, 240, 3)
        and np.array_equal(cv2.flip(flip_h, 1), img)
        and np.array_equal(cv2.flip(flip_v, 0), img)
        and np.array_equal(cv2.flip(flip_both, -1), img)
        and gray.shape == (200, 240)
        and hsv.shape == (200, 240, 3)
        and yuv.shape == (200, 240, 3)
    )
    cases.append(dict(
        name="geometry_and_color_spaces",
        inputs=dict(resize_wh=[120, 100], angle=30, shift=[25, 15]),
        prerequisites="原始 200x240 BGR 图像",
        action="测试 resize、切片裁剪、旋转/平移仿射、三向 flip 可逆性,以及 BGR 到 GRAY/HSV/YUV 颜色空间转换。",
        expected=dict(
            resized_shape=[100, 120, 3],
            cropped_shape=[100, 120, 3],
            flips_reversible=True,
            gray_shape=[200, 240],
        ),
        actual=dict(
            resized_shape=list(resized.shape),
            cropped_shape=list(cropped.shape),
            flips_reversible=bool(
                np.array_equal(cv2.flip(flip_h, 1), img)
                and np.array_equal(cv2.flip(flip_v, 0), img)
                and np.array_equal(cv2.flip(flip_both, -1), img)
            ),
            gray_shape=list(gray.shape),
        ),
        measurements=dict(
            center_gray=int(gray[100, 100]),
            center_hsv=hsv[100, 100].tolist(),
            center_yuv=yuv[100, 100].tolist(),
        ),
        passed=ok2,
    ))

    # 3. Arithmetic, thresholding, and smoothing overview
    a = np.full((60, 60), 200, dtype=np.uint8)
    b_arr = np.full((60, 60), 100, dtype=np.uint8)
    added = cv2.add(a, b_arr)
    subbed = cv2.subtract(b_arr, a)
    blended = cv2.addWeighted(a, 0.7, b_arr, 0.3, 0)

    bimodal = np.full((100, 100), 50, dtype=np.uint8)
    bimodal[20:80, 20:80] = 210
    ret_fix, th_fix = cv2.threshold(bimodal, 127, 255, cv2.THRESH_BINARY)
    th_adap = cv2.adaptiveThreshold(bimodal, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    ret_otsu, th_otsu = cv2.threshold(bimodal, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    s_mean = cv2.blur(bimodal, (5, 5))
    s_gauss = cv2.GaussianBlur(bimodal, (5, 5), 0)
    s_med = cv2.medianBlur(bimodal, 5)
    s_bi = cv2.bilateralFilter(bimodal, 9, 75, 75)

    ok3 = (
        int(added[0, 0]) == 255
        and int(subbed[0, 0]) == 0
        and int(blended[0, 0]) == 170
        and int(ret_fix) == 127
        and int(ret_otsu) == 50
        and np.array_equal(th_fix, th_otsu)
        and th_adap.shape == (100, 100)
        and s_mean.shape == s_gauss.shape == s_med.shape == s_bi.shape == (100, 100)
    )
    cases.append(dict(
        name="arithmetic_threshold_smoothing",
        inputs=dict(a_val=200, b_val=100, weights=[0.7, 0.3, 0]),
        prerequisites="固定亮度常量图与双峰 50/210 灰度方块图",
        action="验证饱和加减、加权混合、简单/自适应/Otsu 阈值化以及均值/高斯/中值/双边四种滤波。",
        expected=dict(add_sat=255, sub_sat=0, blend_val=170, otsu_matches_fixed=True),
        actual=dict(
            add_sat=int(added[0, 0]),
            sub_sat=int(subbed[0, 0]),
            blend_val=int(blended[0, 0]),
            otsu_matches_fixed=bool(np.array_equal(th_fix, th_otsu)),
        ),
        measurements=dict(
            otsu_threshold=float(ret_otsu),
            edge_grad_gauss=int(abs(int(s_gauss[20, 50]) - int(s_gauss[19, 50]))),
            edge_grad_bilateral=int(abs(int(s_bi[20, 50]) - int(s_bi[19, 50]))),
        ),
        passed=ok3,
    ))

    # 4. Edge detection (Canny/Sobel/Laplacian), morphology (erode/dilate/open/close), and contours
    bin_img = np.zeros((120, 160), dtype=np.uint8)
    cv2.rectangle(bin_img, (20, 20), (70, 95), 255, -1)
    cv2.circle(bin_img, (120, 60), 25, 255, -1)
    # Add small noise dot & pinhole to prove opening & closing
    bin_with_defects = bin_img.copy()
    bin_with_defects[5:8, 5:8] = 255
    bin_with_defects[55:58, 42:45] = 0

    edges = cv2.Canny(bin_img, 100, 200)
    sobel_x = cv2.Sobel(bin_img, cv2.CV_64F, 1, 0, ksize=5)
    sobel_y = cv2.Sobel(bin_img, cv2.CV_64F, 0, 1, ksize=5)
    lap = cv2.Laplacian(bin_img, cv2.CV_64F)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    eroded = cv2.erode(bin_img, kernel, iterations=1)
    dilated = cv2.dilate(bin_img, kernel, iterations=1)
    opened = cv2.morphologyEx(bin_with_defects, cv2.MORPH_OPEN, kernel)
    closed = cv2.morphologyEx(bin_with_defects, cv2.MORPH_CLOSE, kernel)

    contours, _ = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    drawn = cv2.cvtColor(bin_img, cv2.COLOR_GRAY2BGR)
    cv2.drawContours(drawn, contours, -1, (0, 255, 0), 3)

    ok4 = (
        int(np.count_nonzero(edges)) > 200
        and float(np.max(np.abs(sobel_x))) > 0
        and float(np.max(np.abs(sobel_y))) > 0
        and float(np.max(np.abs(lap))) > 0
        and int(np.count_nonzero(eroded)) < int(np.count_nonzero(bin_img)) < int(np.count_nonzero(dilated))
        and int(opened[6, 6]) == 0
        and int(closed[56, 43]) == 255
        and len(contours) == 2
    )
    cases.append(dict(
        name="edges_morphology_contours",
        inputs=dict(shapes=2, kernel=[5, 5]),
        prerequisites="含矩形与圆形前景及孤立噪点/小孔洞的 120x160 二值图",
        action="验证 Canny/Sobel/Laplacian 边缘、腐蚀收缩/膨胀扩展、开运算去噪/闭运算填孔,以及外部轮廓检测与绘制。",
        expected=dict(
            erode_lt_orig_lt_dilate=True,
            open_removed_speck=True,
            close_filled_hole=True,
            external_contours=2,
        ),
        actual=dict(
            erode_lt_orig_lt_dilate=(
                int(np.count_nonzero(eroded)) < int(np.count_nonzero(bin_img)) < int(np.count_nonzero(dilated))
            ),
            open_removed_speck=(int(opened[6, 6]) == 0),
            close_filled_hole=(int(closed[56, 43]) == 255),
            external_contours=len(contours),
        ),
        measurements=dict(
            orig_white=int(np.count_nonzero(bin_img)),
            eroded_white=int(np.count_nonzero(eroded)),
            dilated_white=int(np.count_nonzero(dilated)),
            canny_edges=int(np.count_nonzero(edges)),
        ),
        passed=ok4,
    ))

    # 5. Offline VideoWriter + VideoCapture roundtrip (4 frames MJPG AVI)
    with tempfile.TemporaryDirectory() as tmp:
        vid_path = str(Path(tmp) / "demo.avi")
        writer = cv2.VideoWriter(vid_path, cv2.VideoWriter_fourcc(*"MJPG"), 10.0, (80, 60))
        opened_w = writer.isOpened()
        for i in range(4):
            frame = np.full((60, 80, 3), i * 60, dtype=np.uint8)
            writer.write(frame)
        writer.release()

        cap = cv2.VideoCapture(vid_path)
        read_shapes = []
        while cap.isOpened():
            ret, frm = cap.read()
            if not ret:
                break
            read_shapes.append(list(frm.shape))
        cap.release()

    ok5 = opened_w and len(read_shapes) == 4 and all(s == [60, 80, 3] for s in read_shapes)
    cases.append(dict(
        name="video_capture_writer_roundtrip",
        inputs=dict(frames=4, size_wh=[80, 60], fourcc="MJPG"),
        prerequisites="在临时目录写入 4 帧 MJPG AVI 测试视频后使用 cv2.VideoCapture 逐帧读取",
        action="验证 VideoCapture 循环读取全部 4 帧、每帧形状 (60, 80, 3) 及 cap.release() 正常释放。",
        expected=dict(writer_opened=True, frames_read=4, frame_shape=[60, 80, 3]),
        actual=dict(
            writer_opened=bool(opened_w),
            frames_read=len(read_shapes),
            frame_shape=read_shapes[0] if read_shapes else None,
        ),
        measurements=dict(all_shapes_identical=(len(read_shapes) == 4 and all(s == [60, 80, 3] for s in read_shapes))),
        passed=ok5,
    ))

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
预期结果 · 待实际运行核验
  • 核对 200×240 BGR 读写与 ROI/通道、三向翻转、饱和算术、双图形形态学开闭运算与 2 轮廓检出,以及 4 帧 MJPG 视频完整读取。
全链路实测图像属性/读写/ROI/颜色空间/阈值/滤波/边缘/形态学/轮廓与离线视频读取

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

当前源码 SHA256:f82411869f3f53b1d57c9f2d8f25a56099f728e3eb8195722ecc745297534ac1

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载OpenCV 图像处理基础实验

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

ZIP SHA256:62bef4d4031597f587f819830d707a27850f98c7f4976f182c58b1143537c5ea

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 OpenCV 中,为什么 `img.shape` 返回 `(height, width, channels)`,而 `cv2.resize(img, (w, h))` 传入的尺寸却是 `(width, height)`?

展开参考解答

`img.shape` 遵循 NumPy 矩阵的 `(行, 列)` 维度顺序,对应 `(y/高度, x/宽度)`;而 OpenCV 绘图与几何 API(如 `cv2.resize`、`cv2.warpAffine`、`cv2.rectangle`)沿用笛卡尔图像坐标 `(x/宽度, y/高度)`,调用时务必注意二者顺序互换。

规范与官方依据