Last active
December 19, 2015 17:29
-
-
Save ayman/5991581 to your computer and use it in GitHub Desktop.
For any Processing PImage, compute the histogram, the normalized histogram, and the overall Shannon entropy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CVExtras { | |
PImage pImage; | |
int[] hist = new int[256]; // Raw Pixel Counts | |
double[] histN = new double[256]; // Pixel Percentages (Normalized) | |
double entropy; | |
CVExtras(PImage img) { | |
for (int i = 0; i < 256; i++) { | |
this.hist[i] = 0; | |
this.histN[i] = 0.0; | |
} | |
computeHistogram(img); | |
computeEntropy(this.histN); | |
} | |
void computeHistogram(PImage img) { | |
int sum = 0; | |
for (int i = 0; i < img.width; i++) { | |
for (int j = 0; j < img.height; j++) { | |
int bright = int(brightness(img.get(i, j))); | |
this.hist[bright]++; | |
sum += bright; | |
} | |
} | |
for (int i = 0; i < this.hist.length; i++) { | |
this.histN[i] = ((double) this.hist[i]) / sum; | |
} | |
} | |
void computeEntropy(double[] histN) { | |
double e = 0; | |
for (int i = 0; i < histN.length; i++) { | |
double frequency = histN[i]; | |
if (frequency != 0) { | |
e -= frequency * (Math.log(frequency) / Math.log(2)); | |
} | |
} | |
this.entropy = Double.isNaN(e) ? 0.0 : e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment