如何对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 ofcalcHist()into a 1D array thatpolyfitcan 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

