Reputation: 107
So here is my code for getting the variance (and standard deviation) of red colour values. I have done the same for Green and Blue.
/*Red Variance*/
public static double varianceRed(BufferedImage image){
Color r = new Color(image.getRGB(0, 0));
double mean = meanValueRed(image);
double sumOfDiff = 0.0;
for (int y = 0; y < image.getHeight(); ++y){
for (int x = 0; x < image.getWidth(); ++x){
double colour = r.getRed() - mean;
sumOfDiff += Math.pow(colour, 2);
}
}
return sumOfDiff / ((image.getWidth() * image.getHeight()) - 1);
}
/*Red Standard Deviation*/
public static double standardDeviationRed(BufferedImage image){
return Math.sqrt(varianceRed(image));
}
My problem is, that each method for r,g,b returns back a variance of 0.0 and I really just can't wrap my head around why. I have done the same for the mean brightness value using Java's raster and it works fine. Now I can't understand why colour is not working. I have tried everything. Any idea as to why I am getting 0.0 and how It could be fixed?
Upvotes: 0
Views: 2132
Reputation: 27114
You need to get the pixel of every color inside the loop, not just the one at (0,0):
public static double varianceRed(BufferedImage image) {
double mean = meanValueRed(image);
double sumOfDiff = 0.0;
for (int y = 0; y < image.getHeight(); ++y) {
for (int x = 0; x < image.getWidth(); ++x) {
Color r = new Color(image.getRGB(x, y)); // Moved inside loop, with proper indexes
double colour = r.getRed() - mean;
sumOfDiff += Math.pow(colour, 2);
}
}
return sumOfDiff / ((image.getWidth() * image.getHeight()) - 1);
}
PS: You also seem to have a bug in your code for images of size 1x1. ;-)
Upvotes: 1