package com.imageretrieval.features;
import java.awt.Color;
import com.imageretrieval.utils.Pixel;
public class RGBColorHistogram {
public static void main(String[] args) {
Pixel[][] matrix = getImagePixel("", 200, 200);
Pixel[][] matrix1 = getImagePixel("", 200, 200);
int[][] histogram = new int[3][256];
int[][] histogram1 = new int[3][256];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
histogram[0][matrix[i][j].red]++;
histogram[1][matrix[i][j].green]++;
histogram[2][matrix[i][j].blue]++;
histogram1[0][matrix1[i][j].red]++;
histogram1[1][matrix1[i][j].green]++;
histogram1[2][matrix1[i][j].blue]++;
}
}
int[] vector = matrix2vector(histogram);
int[] vector1 = matrix2vector(histogram1);
double len = 0, len1 = 0, numerator = 0;
for(int i = 0; i < vector.length; i++){
len += Math.pow(vector[i], 2);
len1 += Math.pow(vector1[i], 2);
numerator += vector[i] * vector1[i];
}
len = Math.sqrt(len);
len1 = Math.sqrt(len1);
System.out.println(numerator / (len * len1));
}
public static Pixel[][] getImagePixel(String imagePath, int width, int height) {
BufferedImage bi = null;
try {
bi = resizeImage(imagePath, width, height, BufferedImage.TYPE_INT_RGB);
} catch (Exception e) {
e.printStackTrace();
return null;
}
int minx = bi.getMinX();
int miny = bi.getMinY();
Pixel[][] rgbMatrix = new Pixel[width - minx][height - miny];
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j);
int red = (pixel & 0xff0000) >> 16;
int green = (pixel & 0xff00) >> 8;
int blue = (pixel & 0xff);
Pixel p = new Pixel();
p.red = red;
p.green = green;
p.blue = blue;
rgbMatrix[i - minx][j - miny] = p;
}
}
return rgbMatrix;
}
public static BufferedImage resizeImage(String srcImgPath, int width, int height, int imageType)
throws IOException {
File srcFile = new File(srcImgPath);
BufferedImage srcImg = ImageIO.read(srcFile);
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, imageType);
buffImg.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
return buffImg;
}
public static int[] matrix2vector(int[][] matrix){
if(matrix.length <= 0 || matrix[0].length <= 0){
return null;
}
int[] vector = new int[matrix.length * matrix[0].length];
int index = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++, index++){
vector[index] = matrix[i][j];
}
}
return vector;
}
}