"""Offline OpenCV lab for Ch15: image histogram, equalization, CLAHE & comparison."""
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_low_contrast_gray() -> np.ndarray:
"""120x160 low-contrast grayscale image concentrated in intensity [60, 120]."""
y, x = np.mgrid[0:120, 0:160]
base = 65.0 + 35.0 * (x / 159.0) + 12.0 * np.sin(y / 12.0)
img = np.clip(np.round(base), 0, 255).astype(np.uint8)
cv2.circle(img, (80, 60), 28, 118, -1)
cv2.rectangle(img, (20, 20), (50, 55), 58, -1)
return img
def build_color_bgr() -> np.ndarray:
"""120x160 synthetic BGR image with distinct channel distributions."""
b = np.clip(40 + np.tile(np.linspace(0, 80, 160), (120, 1)), 0, 255).astype(np.uint8)
g = np.clip(70 + np.tile(np.linspace(0, 90, 120)[:, None], (1, 160)), 0, 255).astype(np.uint8)
r = np.full((120, 160), 110, dtype=np.uint8)
cv2.circle(r, (80, 60), 35, 195, -1)
return cv2.merge([b, g, r])
def run_cases(fig_dir: Path | None):
cases = []
figures = {}
gray = build_low_contrast_gray()
total_px = int(gray.size)
# Case 1: Grayscale calcHist with and without mask
hist_full = cv2.calcHist([gray], [0], None, [256], [0, 256])
mask = np.zeros_like(gray)
mask[20:100, 30:130] = 255 # 80x100 = 8000 pixels
hist_mask = cv2.calcHist([gray], [0], mask, [256], [0, 256])
full_sum = int(hist_full.sum())
mask_sum = int(hist_mask.sum())
min_val, max_val = int(gray.min()), int(gray.max())
hist_bins = int(hist_full.size)
c1_ok = (hist_bins == 256 and full_sum == total_px and mask_sum == 8000
and max_val - min_val < 80)
cases.append(dict(
name="grayscale_calchist_and_mask",
inputs=dict(shape=[120, 160], histSize=[256], ranges=[0, 256], mask_area=8000),
prerequisites="120x160 低对比度灰度图(像素集中在 53–118)与 80x100 中心掩码",
action="分别在无掩码和有掩码条件下调用 cv2.calcHist(),核对 256 个灰度级 bin(OpenCV 5.1 返回形状 (256,))及频数总和。",
expected=dict(
hist_shape=[256],
full_pixel_sum=19200,
mask_pixel_sum=8000,
low_contrast_span_lt_80=True,
),
actual=dict(
hist_shape=list(hist_full.shape),
full_pixel_sum=full_sum,
mask_pixel_sum=mask_sum,
low_contrast_span_lt_80=(max_val - min_val) < 80,
),
measurements=dict(orig_min=min_val, orig_max=max_val, orig_std=round(float(gray.std()), 2)),
passed=c1_ok,
))
# Case 2: Global equalizeHist vs CLAHE & BGR per-channel equalization
eq_gray = cv2.equalizeHist(gray)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
clahe_gray = clahe.apply(gray)
orig_std = round(float(gray.std()), 2)
eq_std = round(float(eq_gray.std()), 2)
clahe_std = round(float(clahe_gray.std()), 2)
bgr = build_color_bgr()
b, g, r = cv2.split(bgr)
bgr_eq = cv2.merge([cv2.equalizeHist(b), cv2.equalizeHist(g), cv2.equalizeHist(r)])
ch_means_before = [round(float(ch.mean()), 2) for ch in (b, g, r)]
ch_means_after = [round(float(ch.mean()), 2) for ch in cv2.split(bgr_eq)]
c2_ok = (int(eq_gray.min()) == 0 and int(eq_gray.max()) == 255
and eq_std > orig_std * 3.0 and clahe_std > orig_std and bgr_eq.shape == bgr.shape)
cases.append(dict(
name="equalize_hist_clahe_and_bgr",
inputs=dict(clahe_clip=2.0, clahe_grid=[8, 8], color_channels=3),
prerequisites="低对比度灰度图与 3 通道合成 BGR 彩图",
action="执行 cv2.equalizeHist()、cv2.createCLAHE() 及分通道 BGR 均衡化,核对动态范围拉伸与标准差提升。",
expected=dict(
eq_full_dynamic_range=True,
eq_std_gt_3x_orig=True,
clahe_increases_std=True,
bgr_eq_shape=[120, 160, 3],
),
actual=dict(
eq_full_dynamic_range=(int(eq_gray.min()) == 0 and int(eq_gray.max()) == 255),
eq_std_gt_3x_orig=eq_std > orig_std * 3.0,
clahe_increases_std=clahe_std > orig_std,
bgr_eq_shape=list(bgr_eq.shape),
),
measurements=dict(
orig_std=orig_std, eq_std=eq_std, clahe_std=clahe_std,
bgr_means_before=ch_means_before, bgr_means_after=ch_means_after,
),
passed=c2_ok,
))
# Case 3: compareHist (correlation, chi-square, Bhattacharyya)
bright_shifted = np.clip(gray.astype(np.int16) + 90, 0, 255).astype(np.uint8)
hist_a = cv2.calcHist([gray], [0], None, [256], [0, 256])
hist_b = cv2.calcHist([bright_shifted], [0], None, [256], [0, 256])
cv2.normalize(hist_a, hist_a, alpha=1.0, norm_type=cv2.NORM_L1)
cv2.normalize(hist_b, hist_b, alpha=1.0, norm_type=cv2.NORM_L1)
corr_self = round(float(cv2.compareHist(hist_a, hist_a, cv2.HISTCMP_CORREL)), 6)
corr_diff = round(float(cv2.compareHist(hist_a, hist_b, cv2.HISTCMP_CORREL)), 6)
bhat_self = round(float(cv2.compareHist(hist_a, hist_a, cv2.HISTCMP_BHATTACHARYYA)), 6)
bhat_diff = round(float(cv2.compareHist(hist_a, hist_b, cv2.HISTCMP_BHATTACHARYYA)), 6)
c3_ok = (corr_self == 1.0 and corr_diff < 0.2 and bhat_self == 0.0 and bhat_diff > 0.8)
cases.append(dict(
name="compare_hist_similarity",
inputs=dict(brightness_shift=90, methods=["HISTCMP_CORREL", "HISTCMP_BHATTACHARYYA"]),
prerequisites="归一化后的原始灰度图直方图与亮度偏移 +90 后的直方图",
action="调用 cv2.compareHist() 对比同图与亮度偏移图的相关性及巴氏距离。",
expected=dict(
self_correl_is_1=True,
shifted_correl_lt_02=True,
self_bhattacharyya_is_0=True,
shifted_bhattacharyya_gt_08=True,
),
actual=dict(
self_correl_is_1=corr_self == 1.0,
shifted_correl_lt_02=corr_diff < 0.2,
self_bhattacharyya_is_0=bhat_self == 0.0,
shifted_bhattacharyya_gt_08=bhat_diff > 0.8,
),
measurements=dict(
corr_self=corr_self, corr_diff=corr_diff,
bhat_self=bhat_self, bhat_diff=bhat_diff,
),
passed=c3_ok,
))
# Case 4: Matplotlib 2x2 histogram & equalization comparison 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)
hist_eq = cv2.calcHist([eq_gray], [0], None, [256], [0, 256])
hist_clahe = cv2.calcHist([clahe_gray], [0], None, [256], [0, 256])
fig, axes = plt.subplots(2, 2, figsize=(9.2, 6.2), dpi=140)
axes[0, 0].imshow(gray, cmap="gray", vmin=0, vmax=255)
axes[0, 0].set_title(f"原始低对比度灰度图 (std={orig_std:.2f})", fontsize=10)
axes[0, 0].axis("off")
axes[0, 1].imshow(eq_gray, cmap="gray", vmin=0, vmax=255)
axes[0, 1].set_title(f"直方图均衡化 equalizeHist (std={eq_std:.2f})", fontsize=10)
axes[0, 1].axis("off")
axes[1, 0].plot(hist_full.ravel(), color="#1f5a99", lw=1.6, label="原图直方图")
axes[1, 0].plot(hist_clahe.ravel(), color="#1e8449", lw=1.3, alpha=0.85, label=f"CLAHE (std={clahe_std:.2f})")
axes[1, 0].set_xlim(0, 255)
axes[1, 0].set_xlabel("像素灰度级 (0–255)")
axes[1, 0].set_ylabel("像素频数")
axes[1, 0].set_title("原图与 CLAHE 灰度直方图对比", fontsize=10)
axes[1, 0].grid(True, linestyle="--", alpha=0.35)
axes[1, 0].legend(fontsize=8.5)
axes[1, 1].plot(hist_eq.ravel(), color="#c0392b", lw=1.6, label="equalizeHist 全局均衡")
axes[1, 1].set_xlim(0, 255)
axes[1, 1].set_xlabel("像素灰度级 (0–255)")
axes[1, 1].set_ylabel("像素频数")
axes[1, 1].set_title("全局均衡化后直方图分布 (0–255 铺满)", fontsize=10)
axes[1, 1].grid(True, linestyle="--", alpha=0.35)
axes[1, 1].legend(fontsize=8.5)
fig.suptitle("OpenCV 图像直方图统计与对比度均衡实测", fontsize=12)
fig.tight_layout()
out_png = fig_dir / "histogram-equalization-comparison.png"
fig.savefig(out_png)
plt.close(fig)
figures["histogram-equalization-comparison.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="histogram_equalization_plot",
inputs=dict(panels=4, figure="histogram-equalization-comparison.png"),
prerequisites="原图、equalizeHist 与 CLAHE 灰度图及其 256-bin 直方图",
action="输出 2×2 图像与直方图分布对比 PNG。",
expected=dict(panel_count=4, eq_span=255),
actual=dict(panel_count=4, eq_span=int(eq_gray.max()) - int(eq_gray.min())),
measurements=dict(figure_generated="histogram-equalization-comparison.png" in figures),
passed=(int(eq_gray.max()) - int(eq_gray.min())) == 255,
))
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-image-histogram-lab/explore-image-histogram.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-image-histogram.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a584.zip