OpenCV 图像直方图
核对灰度与彩色直方图统计、掩码局部统计、全局均衡化与 CLAHE 对比度增强,以及直方图相似度比较的 OpenCV 5.1.0 实测数据与对比图。
学完这一章,你能够
- 核对灰度与彩色直方图统计、掩码局部统计、全局均衡化与 CLAHE 对比度增强,以及直方图相似度比较的 OpenCV 5.1.0 实测数据与对比图。
图像直方图概念与 cv2.calcHist() 计算
图像直方图以横轴表示像素强度级(0–255)、纵轴表示对应强度的像素频数,用于直观刻画图像亮度分布与对比度特征:峰群挤在低灰度区表明画面偏暗,集中在窄区间说明对比度偏低,铺展均匀则层次丰富。灰度直方图统计单通道灰度级频数,颜色直方图则分别统计彩色图像 BGR 各通道分布。
`cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])` 要求 `images` 传入列表(如 `[img]`),`channels` 指定通道索引(灰度为 `[0]`,BGR 彩图分别为 `[0]`/`[1]`/`[2]`),`mask` 可选用于限定局部统计区域(全图传 `None`),`histSize=[256]` 与 `ranges=[0, 256]` 覆盖 0–255 全部强度级,`accumulate=True` 支持跨图累加。本站实测在 120×160 低对比度灰度图(像素集中在 `53–118`,标准差 `17.49`)上统计:全图频数总和精确等于 `19200`,施加 80×100 中心掩码后总和为 `8000`;需注意 OpenCV 5.1.0 中 1D `calcHist` 返回数组形状为 `(256,)`(早期 4.x 为 `(256, 1)`),绘图或切片时使用 `.ravel()` 可兼容两代版本。
直方图均衡化、彩色通道处理与相似度比较
全局直方图均衡化(`cv2.equalizeHist(image)`)依据累积分布函数重新映射灰度级以拉宽动态范围、显著提升对比度。本站实测上述低对比度图经 `equalizeHist` 后像素铺满 `[0, 255]`,灰度标准差由 `17.49` 大幅升至 `75.98`;补充实测限制对比度自适应直方图均衡 `cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))` 标准差温和提升至 `19.23`,可避免全局均衡在平坦背景区过度放大噪声。
对彩色图像可循环遍历 BGR 三个通道分别调用 `cv2.calcHist()` 绘制三色分布曲线,也可先用 `cv2.split()` 拆分 B/G/R 通道分别做 `cv2.equalizeHist()` 再由 `cv2.merge()` 合成。实测对合成 120×160 BGR 彩图分通道均衡后,三通道均值由 `[79.51, 114.51, 127.06]` 重分布为 `[127.49, 126.95, 51.17]`(工程上若要避免色偏,也可转换到 YCrCb/Lab 空间仅均衡亮度通道)。
`cv2.compareHist(hist1, hist2, method)` 用于量化两幅直方图的相似度,常用方法包括相关性 `cv2.HISTCMP_CORREL`(越接近 1 越相似)与巴氏距离 `cv2.HISTCMP_BHATTACHARYYA`(越接近 0 越相似)。本站实测将 L1 归一化后的原图直方图分别与自身及亮度整体偏移 `+90` 的图像对比:自比较相关性为 `1.0`、巴氏距离为 `0.0`,与偏移图比较相关性降至 `-0.127741`、巴氏距离升至 `1.0`。结合均衡化、阈值分割、图像检索与颜色校正,直方图构成了经典图像处理的基础分析工具。
OpenCV 图像直方图核心函数对照
| 功能 | 函数 | 说明 |
| 计算直方图 | `cv2.calcHist()` | 统计单通道或多通道像素强度频数分布,支持掩码与累加。 |
| 直方图均衡化 | `cv2.equalizeHist()` | 按累积分布拉伸灰度动态范围,显著增强对比度(局部增强可用 CLAHE)。 |
| 直方图比较 | `cv2.compareHist()` | 通过相关性、卡方或巴氏距离评估两幅直方图相似度。 |
| 绘制直方图 | `matplotlib.pyplot.plot()` | 将统计得到的直方图频数数组可视化为强度分布曲线。 |
运行灰度/掩码直方图、全局均衡化、CLAHE 与直方图比较实验
展开查看收起
"""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)
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
B、G、R 三通道独立拉伸会改变各像素的通道比例从而引起偏色;工程上通常先转换到 YCrCb 或 Lab 颜色空间,仅对亮度通道(Y 或 L)做均衡化或 CLAHE,再转回 BGR。