"""Offline OpenCV lab for Ch22: filter effects (gray, vintage/sepia, emboss, blur, sharpen, Canny, stylization)."""
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_colorful_scene() -> np.ndarray:
"""Create a 160x220 synthetic BGR scene with sky gradient, sun, hills, and crisp blocks."""
h, w = 160, 220
img = np.zeros((h, w, 3), dtype=np.uint8)
# Sky gradient (BGR: blue strong at top)
for r in range(h):
t = r / (h - 1)
img[r, :, 0] = int(215 - 90 * t)
img[r, :, 1] = int(165 - 40 * t)
img[r, :, 2] = int(105 + 45 * t)
# Warm sun
cv2.circle(img, (172, 38), 20, (40, 200, 250), -1)
# Green mountain polygon
mtn = np.array([[0, 160], [65, 78], [135, 128], [185, 92], [220, 160]], dtype=np.int32)
cv2.fillPoly(img, [mtn], (55, 140, 65))
# Colorful crisp building blocks in foreground
cv2.rectangle(img, (20, 100), (62, 152), (45, 75, 205), -1)
cv2.rectangle(img, (28, 110), (40, 124), (235, 240, 245), -1)
cv2.rectangle(img, (46, 110), (56, 124), (235, 240, 245), -1)
cv2.rectangle(img, (84, 115), (128, 152), (185, 115, 45), -1)
cv2.line(img, (0, 152), (220, 152), (35, 35, 35), 2)
return img
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
bgr = build_colorful_scene()
# Case 1: Grayscale & Sepia/Vintage filter (simultaneous channel weighting vs sequential overwrite bug)
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
b0, g0, r0 = [ch.astype(np.float32) for ch in cv2.split(bgr)]
r_sep = np.clip(r0 * 0.393 + g0 * 0.769 + b0 * 0.189, 0, 255).astype(np.uint8)
g_sep = np.clip(r0 * 0.349 + g0 * 0.686 + b0 * 0.168, 0, 255).astype(np.uint8)
b_sep = np.clip(r0 * 0.272 + g0 * 0.534 + b0 * 0.131, 0, 255).astype(np.uint8)
vintage = cv2.merge((b_sep, g_sep, r_sep))
# Demonstrate how sequential in-place overwrite differs from standard simultaneous matrix formula
b_seq, g_seq, r_seq = cv2.split(bgr)
r_seq = np.clip(r_seq * 0.393 + g_seq * 0.769 + b_seq * 0.189, 0, 255).astype(np.uint8)
g_seq = np.clip(r_seq * 0.349 + g_seq * 0.686 + b_seq * 0.168, 0, 255).astype(np.uint8)
b_seq = np.clip(r_seq * 0.272 + g_seq * 0.534 + b_seq * 0.131, 0, 255).astype(np.uint8)
vintage_seq = cv2.merge((b_seq, g_seq, r_seq))
overwrite_diff = round(float(np.mean(np.abs(vintage.astype(np.float32) - vintage_seq.astype(np.float32)))), 3)
v_b_mean = round(float(b_sep.mean()), 2)
v_g_mean = round(float(g_sep.mean()), 2)
v_r_mean = round(float(r_sep.mean()), 2)
c1_ok = (gray.shape == (160, 220) and vintage.shape == (160, 220, 3)
and v_r_mean > v_g_mean > v_b_mean and overwrite_diff > 5.0)
cases.append(dict(
name="grayscale_and_vintage_sepia",
inputs=dict(shape=[160, 220, 3], sepia_weights=[[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]),
prerequisites="160×220 合成彩色场景图(蓝天、太阳、绿山与前景建筑)",
action="执行 cv2.cvtColor 灰度化与 BGR 通道加权怀旧滤镜,核对暖色调均值排序 R > G > B 及原地覆盖写法的数值偏差。",
expected=dict(
gray_shape=[160, 220],
vintage_warm_order_r_gt_g_gt_b=True,
inplace_overwrite_causes_drift=True,
),
actual=dict(
gray_shape=list(gray.shape),
vintage_warm_order_r_gt_g_gt_b=(v_r_mean > v_g_mean > v_b_mean),
inplace_overwrite_causes_drift=overwrite_diff > 5.0,
),
measurements=dict(
gray_mean=round(float(gray.mean()), 2),
vintage_means_bgr=[v_b_mean, v_g_mean, v_r_mean],
seq_overwrite_mae=overwrite_diff,
),
passed=c1_ok,
))
# Case 2: Emboss, GaussianBlur (15x15), Sharpen (filter2D), and Canny (100, 200)
emboss_kernel = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]], dtype=np.float32)
emboss = cv2.filter2D(gray, -1, emboss_kernel)
blurred = cv2.GaussianBlur(bgr, (15, 15), 0)
sharpen_kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=np.float32)
sharpened = cv2.filter2D(bgr, -1, sharpen_kernel)
edges = cv2.Canny(gray, 100, 200)
# Measure sharpness via Laplacian variance on grayscale versions
var_orig = round(float(cv2.Laplacian(gray, cv2.CV_64F).var()), 2)
var_blur = round(float(cv2.Laplacian(cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY), cv2.CV_64F).var()), 2)
var_sharp = round(float(cv2.Laplacian(cv2.cvtColor(sharpened, cv2.COLOR_BGR2GRAY), cv2.CV_64F).var()), 2)
edge_px = int(np.count_nonzero(edges))
c2_ok = (var_blur < var_orig * 0.25 and var_sharp > var_orig * 2.0
and emboss.shape == gray.shape and edge_px > 500)
cases.append(dict(
name="emboss_blur_sharpen_and_canny",
inputs=dict(blur_ksize=[15, 15], canny=[100, 200]),
prerequisites="合成彩色场景图与对应灰度图",
action="依次应用浮雕卷积核、15×15 高斯模糊、锐化卷积核与 Canny(100,200) 滤镜,对比拉普拉斯方差清晰度变化与边缘像素数。",
expected=dict(
blur_reduces_sharpness=True,
sharpen_boosts_sharpness=True,
emboss_shape=[160, 220],
canny_edges_gt_500=True,
),
actual=dict(
blur_reduces_sharpness=var_blur < var_orig * 0.25,
sharpen_boosts_sharpness=var_sharp > var_orig * 2.0,
emboss_shape=list(emboss.shape),
canny_edges_gt_500=edge_px > 500,
),
measurements=dict(
lap_var_orig=var_orig,
lap_var_blur=var_blur,
lap_var_sharpen=var_sharp,
emboss_mean=round(float(emboss.mean()), 2),
canny_edge_pixels=edge_px,
),
passed=c2_ok,
))
# Case 3: Built-in OpenCV photo stylization & pencilSketch artistic filters
stylized = cv2.stylization(bgr, sigma_s=60, sigma_r=0.45)
sketch_gray, sketch_color = cv2.pencilSketch(bgr, sigma_s=60, sigma_r=0.07, shade_factor=0.05)
c3_ok = (stylized.shape == bgr.shape and sketch_gray.shape == gray.shape and sketch_color.shape == bgr.shape)
cases.append(dict(
name="builtin_stylization_and_pencil_sketch",
inputs=dict(sigma_s=60, stylization_sigma_r=0.45, sketch_sigma_r=0.07),
prerequisites="同一 160×220 合成彩色场景图",
action="调用 OpenCV 内置艺术滤镜 cv2.stylization() 与 cv2.pencilSketch(),核对输出尺寸与灰度/彩色素描双输出。",
expected=dict(
stylized_shape=[160, 220, 3],
sketch_gray_shape=[160, 220],
sketch_color_shape=[160, 220, 3],
),
actual=dict(
stylized_shape=list(stylized.shape),
sketch_gray_shape=list(sketch_gray.shape),
sketch_color_shape=list(sketch_color.shape),
),
measurements=dict(
stylized_std=round(float(stylized.std()), 2),
sketch_gray_mean=round(float(sketch_gray.mean()), 2),
),
passed=c3_ok,
))
# Case 4: Matplotlib 2x3 filter gallery figure
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)
fig, axes = plt.subplots(2, 3, figsize=(9.6, 5.8), dpi=140)
panels = [
(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), "原始合成彩图 (BGR→RGB)", None),
(gray, "灰度滤镜 cvtColor", "gray"),
(cv2.cvtColor(vintage, cv2.COLOR_BGR2RGB), "怀旧滤镜 (Sepia 通道加权)", None),
(emboss, "浮雕滤镜 filter2D", "gray"),
(cv2.cvtColor(blurred, cv2.COLOR_BGR2RGB), "高斯模糊 GaussianBlur (15×15)", None),
(edges, f"边缘检测 Canny (边缘={edge_px}px)", "gray"),
]
for ax, (im, title, cmap) in zip(axes.ravel(), panels):
if cmap:
ax.imshow(im, cmap=cmap, vmin=0, vmax=255)
else:
ax.imshow(im)
ax.set_title(title, fontsize=9.8)
ax.axis("off")
fig.suptitle("OpenCV 常见图像滤镜效果实测对比", fontsize=12)
fig.tight_layout()
out_png = fig_dir / "filter-effects-gallery.png"
fig.savefig(out_png)
plt.close(fig)
figures["filter-effects-gallery.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="filter_effects_gallery_plot",
inputs=dict(panels=6, figure="filter-effects-gallery.png"),
prerequisites="原图及灰度、怀旧、浮雕、模糊与边缘检测滤镜实测输出",
action="输出 2×3 滤镜效果实测对比画廊 PNG。",
expected=dict(panel_count=6, edges_nonempty=True),
actual=dict(panel_count=6, edges_nonempty=edge_px > 0),
measurements=dict(figure_generated="filter-effects-gallery.png" in figures),
passed=edge_px > 0,
))
payload = dict(version=platform.python_version(), opencv=cv2.__version__, 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-filter-effects-lab/explore-filter-effects.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-filter-effects.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a577.zip