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

如何对OpenCV calcHist()生成的直方图执行polyfit()拟合?

Hey there! Let's figure out what's going wrong here. That error is telling you exactly the problem—your x array and histr array don't have the same number of elements, which polyfit requires to work properly.

The Root of the Error

Looking at your line where you define x:

x = np.linspace(0,histr.shape[0],1); # <== ERROR HERE

The third argument to np.linspace is the number of points you want. You've set it to 1, so x ends up being a single value. But histr has 32 elements (since you specified [32] bins in calcHist). That's why you're getting the "expected x and y to have same length" TypeError.

On top of that, cv.calcHist() returns a 2D array (shape (32, 1)), while polyfit expects a 1D array for the y-values.

Fixed Code

Here's your code with the necessary adjustments to get the polynomial fitting working:

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
import numpy.polynomial.polynomial as poly

img = cv.imread('SomeImage.jpg')
color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv.calcHist([img],[i],None,[32],[0,256])
    plt.plot(histr, color = col, label=f'{col} original')
    plt.xlim([0,32])
    
    # Create x array matching the number of histogram bins (32 points)
    x = np.arange(histr.shape[0])  # Gives [0, 1, 2, ..., 31]
    
    # Flatten histr to 1D and run polynomial fit
    coefficients = poly.polyfit(x, histr.flatten(), 4)
    
    # Generate the fitted curve and plot it
    fitted_curve = poly.polyval(x, coefficients)
    plt.plot(x, fitted_curve, linestyle='--', color=col, label=f'{col} fitted')

plt.legend()
plt.show()

Key Fixes Explained

  • Matching x array length: np.arange(histr.shape[0]) creates an array of integers from 0 to 31, which perfectly matches the 32 bins in your histogram.
  • Flattening the histogram: histr.flatten() converts the 2D output of calcHist() into a 1D array that polyfit can process.
  • Optional fitted curve plot: I added code to generate and plot the fitted polynomial so you can visually compare it to the original histogram.

内容的提问来源于stack exchange,提问作者meaning-matters

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:02:54