我正在尝试做与这篇文章类似的事情:Getting dominant colour value from HSV Histogram
我有一张图片,想从中提取主色(色调)。我已经到了计算直方图的地步,并从 minMaxLoc 获得了 maxValue。但是我从 Core.MinMaxLocResult 检索的数字完全没有意义。我得到了 806924 和 1067036 之类的东西; Hue 的期望值不应该在 0 到 180 之间吗?
直方图应该归一化吗?为何如此?我见过像“equalizeHist”和“normalize”这样的方法,但真的不知道如何使用这些方法以及它们将如何帮助我。
此外,一旦我得到一个合理的“最常出现的”色相数,我如何将其转换为实际的色相(例如“绿色是该图像中最常出现的颜色”)?是否有标准的 Hue 范围?比如 0-10 是红色,10-20 是紫色等等?
更新:这是我的代码:
private void processImage(String imgFilename) {
channels = new MatOfInt[] { new MatOfInt(0), new MatOfInt(1),
new MatOfInt(2) };
histSize = new MatOfInt(histSizeNum);
hRanges = new MatOfFloat(0f, 180f); // hue varies from 0 to 179
// use openCV stuff to convert from RGB to HLS space
Mat src = Highgui.imread(imgFilename);
Mat hls = new Mat();// destination color space
Imgproc.cvtColor(src, hls, Imgproc.COLOR_RGB2HLS);
Core.split(hls, hlsChannels);
Mat hue = hlsChannels.get(0);
Mat lum = hlsChannels.get(1);
Mat sat = hlsChannels.get(2);
// we compute the histogram from the 0-th channel for hue
Imgproc.calcHist(Arrays.asList(hls), channels[0], new Mat(), hist,
histSize, hRanges);
Core.normalize(hist, hist, 0,2, Core.NORM_MINMAX, -1, new Mat());
Core.MinMaxLocResult result = Core.minMaxLoc(hist);
// max value should contain the most-recurring Hue value.
double mostOccurringHue = result.maxVal;
double leastOccurringHue = result.minVal;
//double mostOccurringHue = result.maxLoc.x;
//double leastOccurringHue = result.minLoc.x;
// print out for sanity checking
System.out.println("MAX HUE = " + Double.toString(mostOccurringHue) +"\n");
System.out.println("MIN HUE = " + Double.toString(leastOccurringHue) +"\n");
我没有使用 openCV 的 ibuilt 方法来计算直方图及其归一化,而是编写了自己的代码,因为我们仅为色调 channel 创建直方图。看看我的代码。
int main()
{
Mat input = imread("jan31/class4Jan31.jpg",1);
Mat hsv_input;
int h_bins = 5;
Mat hist_input = Mat::zeros( 1, h_bins, CV_32FC1);
int h_range = 179;
int totalNumberPixels = 0;
cvtColor(input, hsv_input, CV_RGB2HSV);
Mat hsv_channels[3];
split( hsv_input, hsv_channels );
for (int i=0; i<hsv_channels[0].rows; i++)
{
for (int j=0; j<hsv_channels[0].cols; j++)
{
if( (int)hsv_channels[1].at<uchar>(i,j)>10 && (int)hsv_channels[1].at<uchar>(i,j)>100)
{
totalNumberPixels++;
int pixel_value = (int)hsv_channels[0].at<uchar>(i,j);
int corresponding_bin = ( pixel_value * h_bins ) / h_range;
hist_input.at<float>( 0, corresponding_bin ) = ( hist_input.at<float>( 0, corresponding_bin ) + 1 );
}
}
}
cout<<"\n total pixels: "<<totalNumberPixels;
for(int i=0; i<hist_input.rows; i++)
{
for (int j=0; j<hist_input.cols; j++)
{
float pixel = hist_input.at<float>(i,j);
hist_input.at<float>(i,j) = pixel / totalNumberPixels;
pixel = hist_input.at<float>(i,j);
cout<<"\n Pixel: "<<pixel;
}
}
cv::waitKey(0);
return 0;
}
我是一名优秀的程序员,十分优秀!