You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为OpenCV生成的直方图填充曲线下方区域?

解决OpenCV直方图曲线下方填充问题

你遇到的问题根源是cv2.calcHist仅返回每个bin对应的像素统计值(y轴数据),没有提供x轴的bin位置参数,直接传入fill_between会因参数不匹配导致崩溃。只需手动生成x轴的bins数组,就能实现曲线下方区域的填充。

修改后的完整代码如下:

import cv2
import matplotlib.pyplot as plt
import numpy as np

img_histogram = cv2.imread("567.jpg")
colors = ("r")
plt.figure()
plt.title("Histogram")
plt.xlabel("Bins")
plt.ylabel("Pixels of the image")

# 生成x轴的bins数组,对应0到255的区间
x = np.arange(256)

for i, col in enumerate(colors):
    histr = cv2.calcHist([img_histogram], [2], None, [256], [0,256])
    plt.plot(histr, color=col)
    # 填充曲线下方区域,alpha设置透明度避免遮挡曲线
    plt.fill_between(x, histr[:, 0], color=col, alpha=0.3)
    plt.xlim([0, 256])

plt.show()

关键细节说明:

  • x = np.arange(256):生成0到255的整数数组,对应直方图的256个bin位置,作为fill_between的x轴参数。
  • histr[:, 0]:将OpenCV返回的二维histr数组转为一维,提取每个bin的像素数量作为y轴数据。
  • alpha=0.3:设置填充区域的透明度,让曲线依然清晰可见,更贴近你期望的效果。

内容的提问来源于stack exchange,提问作者Sebs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:05:19