# 图像处理之相似图片识别（直方图应用篇）

0表示极其不同，1表示极其相似（相同）。

H[124] += 1, 而对于彩色RGB像素来说直方图表达有两种方式，一种是单一直方图，另外一

HG, HB, 假设某一个像素点P的RGB值为(4, 231,129), 则对于的直方图计算为HR[4] += 1,

HG[231] += 1, HB[129] += 1, 如此对每个像素点完成统计以后，RGB彩色直方图数据就生成了。

	public void setGreenBinCount(int greenBinCount) {
this.greenBins = greenBinCount;
}

public void setBlueBinCount(int blueBinCount) {
this.blueBins = blueBinCount;
}

public float[] filter(BufferedImage src, BufferedImage dest) {
int width = src.getWidth();
int height = src.getHeight();

int[] inPixels = new int[width*height];
float[] histogramData = new float[redBins * greenBins * blueBins];
getRGB( src, 0, 0, width, height, inPixels );
int index = 0;
int redIdx = 0, greenIdx = 0, blueIdx = 0;
int singleIndex = 0;
float total = 0;
for(int row=0; row<height; row++) {
int ta = 0, tr = 0, tg = 0, tb = 0;
for(int col=0; col<width; col++) {
index = row * width + col;
ta = (inPixels[index] >> 24) & 0xff;
tr = (inPixels[index] >> 16) & 0xff;
tg = (inPixels[index] >> 8) & 0xff;
tb = inPixels[index] & 0xff;
redIdx = (int)getBinIndex(redBins, tr, 255);
greenIdx = (int)getBinIndex(greenBins, tg, 255);
blueIdx = (int)getBinIndex(blueBins, tb, 255);
singleIndex = redIdx + greenIdx * redBins + blueIdx * redBins * greenBins;
histogramData[singleIndex] += 1;
total += 1;
}
}

// start to normalize the histogram data
for (int i = 0; i < histogramData.length; i++)
{
histogramData[i] = histogramData[i] / total;
}

return histogramData;
}

	/**
* Bhattacharyya Coefficient
* http://www.cse.yorku.ca/~kosta/CompVis_Notes/bhattacharyya.pdf
*
* @return
*/
public double modelMatch() {
HistogramFilter hfilter = new HistogramFilter();
float[] sourceData = hfilter.filter(sourceImage, null);
float[] candidateData = hfilter.filter(candidateImage, null);
double[] mixedData = new double[sourceData.length];
for(int i=0; i<sourceData.length; i++ ) {
mixedData[i] = Math.sqrt(sourceData[i] * candidateData[i]);
}

// The values of Bhattacharyya Coefficient ranges from 0 to 1,
double similarity = 0;
for(int i=0; i<mixedData.length; i++ ) {
similarity += mixedData[i];
}

// The degree of similarity
return similarity;
}

10-16 81

10-16 366
07-04 2万+
05-07 7742
01-27 3070
11-28
11-10 1万+