"""Independent offline OpenCV image-thresholding lab: 5 simple modes, adaptive uneven lighting, Otsu bimodal & 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 run_cases(fig_dir: Path | None):
cases = []
figures = {}
# 1. All 5 simple threshold modes on exact boundary probe values
probe = np.array([[0, 50, 127, 128, 200, 255]], dtype=np.uint8)
r_bin, d_bin = cv2.threshold(probe, 127, 255, cv2.THRESH_BINARY)
r_inv, d_inv = cv2.threshold(probe, 127, 255, cv2.THRESH_BINARY_INV)
r_trc, d_trc = cv2.threshold(probe, 127, 255, cv2.THRESH_TRUNC)
r_tz, d_tz = cv2.threshold(probe, 127, 255, cv2.THRESH_TOZERO)
r_tzi, d_tzi = cv2.threshold(probe, 127, 255, cv2.THRESH_TOZERO_INV)
exp_modes = dict(
binary=[0, 0, 0, 255, 255, 255],
binary_inv=[255, 255, 255, 0, 0, 0],
trunc=[0, 50, 127, 127, 127, 127],
tozero=[0, 0, 0, 128, 200, 255],
tozero_inv=[0, 50, 127, 0, 0, 0],
)
act_modes = dict(
binary=d_bin[0].tolist(),
binary_inv=d_inv[0].tolist(),
trunc=d_trc[0].tolist(),
tozero=d_tz[0].tolist(),
tozero_inv=d_tzi[0].tolist(),
)
ok1 = act_modes == exp_modes and r_bin == 127.0
cases.append(dict(
name="simple_threshold_five_modes",
inputs=dict(probe=probe[0].tolist(), thresh=127, maxval=255),
prerequisites="包含临界点 127 与 128 的单行灰度探针数组",
action="依次以 THRESH_BINARY/BINARY_INV/TRUNC/TOZERO/TOZERO_INV 执行 cv2.threshold,核对严格大于阈值的边界规则。",
expected=exp_modes,
actual=act_modes,
measurements=dict(retval=float(r_bin)),
passed=ok1,
))
# 2. Adaptive thresholding under strong uneven illumination gradient
h, w = 160, 240
grad = np.tile(np.linspace(70, 235, w, dtype=np.float32), (h, 1))
fg_mask = np.zeros((h, w), dtype=bool)
# Place dark strokes/shapes across both dark left and bright right halves
stroke_layer = np.zeros((h, w), dtype=np.uint8)
cv2.putText(stroke_layer, "OPEN", (14, 72), cv2.FONT_HERSHEY_SIMPLEX, 1.3, 255, 4)
cv2.putText(stroke_layer, "CV 5", (18, 136), cv2.FONT_HERSHEY_SIMPLEX, 1.3, 255, 4)
cv2.circle(stroke_layer, (195, 55), 22, 255, 4)
cv2.rectangle(stroke_layer, (170, 102), (222, 144), 255, 4)
fg_mask = stroke_layer > 0
uneven = np.clip(grad - fg_mask.astype(np.float32) * 58.0, 0, 255).astype(np.uint8)
_, glob_127 = cv2.threshold(uneven, 127, 255, cv2.THRESH_BINARY)
adap_mean = cv2.adaptiveThreshold(uneven, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 8)
adap_gauss = cv2.adaptiveThreshold(uneven, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 8)
# Dark foreground should become 0 (black) in THRESH_BINARY; compute accuracy against true background (~fg_mask)
gt_white = ~fg_mask
acc_glob = round(float(np.mean((glob_127 == 255) == gt_white)), 4)
acc_mean = round(float(np.mean((adap_mean == 255) == gt_white)), 4)
acc_gauss = round(float(np.mean((adap_gauss == 255) == gt_white)), 4)
ok2 = acc_mean > 0.95 and acc_gauss > 0.95 and acc_mean > acc_glob + 0.20
cases.append(dict(
name="adaptive_threshold_uneven_lighting",
inputs=dict(shape=[h, w], blockSize=15, C=8, gradient=[70, 235]),
prerequisites="左右亮度从 70 渐变到 235 且包含暗色笔画的 160x240 不均匀光照灰度图",
action="对比固定阈值 127 与 ADAPTIVE_THRESH_MEAN_C / ADAPTIVE_THRESH_GAUSSIAN_C 的前景背景分割准确率。",
expected=dict(
adaptive_mean_gt_095=True,
adaptive_gauss_gt_095=True,
beats_global_by_20pct=True,
),
actual=dict(
adaptive_mean_gt_095=(acc_mean > 0.95),
adaptive_gauss_gt_095=(acc_gauss > 0.95),
beats_global_by_20pct=(acc_mean > acc_glob + 0.20),
),
measurements=dict(
global_127_acc=acc_glob,
adaptive_mean_acc=acc_mean,
adaptive_gauss_acc=acc_gauss,
),
passed=ok2,
))
# 3. Otsu's automatic bimodal binarization
rng = np.random.default_rng(2026)
bimodal = np.full((160, 200), 62.0, dtype=np.float32)
gt_fg = np.zeros((160, 200), dtype=bool)
cv2.circle(bimodal, (70, 80), 40, 198.0, -1)
cv2.rectangle(bimodal, (125, 35), (180, 125), 198.0, -1)
gt_fg = bimodal > 130.0
bimodal_noisy = np.clip(bimodal + rng.normal(0.0, 12.0, size=bimodal.shape), 0, 255).astype(np.uint8)
otsu_ret, otsu_bin = cv2.threshold(bimodal_noisy, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
otsu_inv_ret, otsu_inv = cv2.threshold(bimodal_noisy, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
otsu_acc = round(float(np.mean((otsu_bin == 255) == gt_fg)), 4)
inv_complement = bool(np.array_equal(otsu_inv, 255 - otsu_bin))
ok3 = 95.0 <= otsu_ret <= 165.0 and otsu_ret == otsu_inv_ret and otsu_acc > 0.99 and inv_complement
cases.append(dict(
name="otsu_bimodal_binarization",
inputs=dict(bg_mean=62, fg_mean=198, noise_std=12.0),
prerequisites="背景峰值 62、前景峰值 198 且叠加高斯噪声的双峰灰度图",
action="调用 cv2.threshold(..., 0, 255, THRESH_BINARY + THRESH_OTSU) 自动求解最佳全局阈值并核对分割精度与反相一致性。",
expected=dict(
otsu_in_valley=True,
otsu_acc_gt_099=True,
inv_is_exact_complement=True,
),
actual=dict(
otsu_in_valley=(95.0 <= otsu_ret <= 165.0),
otsu_acc_gt_099=(otsu_acc > 0.99),
inv_is_exact_complement=inv_complement,
),
measurements=dict(otsu_threshold=float(otsu_ret), otsu_acc=otsu_acc),
passed=ok3,
))
# 4. Crisp 2x3 matplotlib comparison chart
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=(10.5, 6.2), dpi=140)
panels = [
("不均匀光照原图 (70→235)", uneven),
(f"全局固定阈值 127 (准确率 {acc_glob:.1%})", glob_127),
(f"自适应均值阈值 (准确率 {acc_mean:.1%})", adap_mean),
(f"自适应高斯阈值 (准确率 {acc_gauss:.1%})", adap_gauss),
("双峰含噪图 (峰 62 / 198)", bimodal_noisy),
(f"Otsu 自动二值化 (T={int(otsu_ret)}, 精度 {otsu_acc:.2%})", otsu_bin),
]
for ax, (ttl, im) in zip(axes.ravel(), panels):
ax.imshow(im, cmap="gray", vmin=0, vmax=255)
ax.set_title(ttl, fontsize=9.5)
ax.axis("off")
fig.suptitle("OpenCV 固定阈值、自适应阈值与 Otsu 二值化实测对比", fontsize=12, y=0.98)
fig.tight_layout()
out_png = fig_dir / "thresholding-methods-comparison.png"
fig.savefig(out_png)
plt.close(fig)
figures["thresholding-methods-comparison.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="thresholding_comparison_figure",
inputs=dict(panels=6),
prerequisites="不均匀光照分割对比图与双峰 Otsu 二值化实测结果",
action="生成 6 格阈值化对比图 thresholding-methods-comparison.png。",
expected=dict(panels=6, otsu_threshold_valid=True),
actual=dict(panels=6, otsu_threshold_valid=(95.0 <= otsu_ret <= 165.0)),
measurements=dict(figure_generated="thresholding-methods-comparison.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-thresholding-lab/explore-image-thresholding.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-image-thresholding.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a589.zip