(I'm curious if this was written by your instructor, because it's pretty sloppy stuff... But I digress).
The setup function is doing most of the work - loading images, computing histograms, displaying stuff. I'm not sure why it's loading the second image, since it's unnecessary. It would be better to use createGraphics() to create a buffer for the second image, like so:
- rocks = loadImage("rocks.png");
- size(rocks.width+256, rocks.height*2);
- rocks2 = createGraphics(rocks.width, rocks.height, P2D);
- rocks2.loadPixels();
loadPixels is calling load pixels - it's completely unnecessary.
computeHistogram is counting the number of pixels of different brightnesses (looking at the red channel, it should be using brightness(), but whatever...). It then figures out the maximum brightness, and then uses that value to scale
the histogram so it has values between 0 and 100. I wrote a cleaner version which reads as follows:
- int[] computeHistogram (PImage anImage)
- {
- int histogram[] = new int[256];
- for (int i = anImage.pixels.length-1; i >= 0; --i) {
- int v = (int) brightness(anImage.pixels[i]);
- histogram[v]++;
- }
- int maxV = 0;
- for (int i = 0; i < 256; i++) {
- maxV = max(maxV,histogram[i]);
- }
- for (int i = 0; i < 256; i++) {
- histogram[i] = (int) (histogram[i]*100.0/maxV);
- }
- return histogram;
- }
brighten() is the function that brightens an image. It walks thru (the completely unnecessary) array and attempts to brighten the image to your instructor's specifications. It's not quite right. This is better:
- for (int i = rocks.pixels.length-1; i >= 0; --i) {
- int v = rocks.pixels[i];
- float br = brightness(v);
- float r = constrain(br*-.004436+2.1308*red(v),0,255);
- float g = constrain(br*-.004436+2.1308*green(v),0,255);
- float b = constrain(br*-.004436+2.1308*blue(v),0,255);
- rocks2.pixels[i] = color(r,g,b);
- }
drawHistogram is supposed to draw the histogram on the screen. It would be cleaner if you passed it the x/y coords of the top/left of the histogram, so you can control it's placement, like so:
- void drawHistogram(int histogram[], int x, int y) {
- noStroke();
- fill(0);
- stroke(255);
- rect(x, y, 256, 256);
- for (int i = 0; i < 256; i++) {
- line(x + i, y+256, x + i, y+256 - histogram[i]);
- }
- }