Willkommen auf unserem Seminar-Blog

Immer auf dem aktuellen Stand bleiben

Dieser Seminar-Blog befindet sich noch im Aufbau und wird in den kommenden Tagen entsprechend verfeinert.

Member Login

Lost your password?

Registration is closed

Sorry, you are not allowed to register by yourself on this site!

You must either be invited by one of our team member or request an invitation by email at viad.info {at} zhdk {dot} ch.

04 getAverageColor()

Februar 28, 2012

Bei dieser Aufgabe soll eine Funktion programmiert werden, der den Durchschnittsfarbwert von einer gewissen Fläche in einem Bild zurückgibt. Der Mittelpunkt der Fläche wird anhand des Mausklicks bestimmt. Sourcecode
PImage img;
int w = 30;

void setup() {
  size(500,330);
  img = loadImage( "1.jpg" );
}

void draw() {

  image(img,0,0);

  int xstart = constrain(mouseX-w/2,0,img.width);
  int ystart = constrain(mouseY-w/2,0,img.height);
  int xend = constrain(mouseX + w/2,0,img.width);
  int yend = constrain(mouseY + w/2,0,img.height);

  color avrColor = getAverageColor(img,xstart,ystart,xend,yend,w,w);

  noStroke();
  fill(avrColor);
  ellipseMode(CORNER);
  ellipse(xstart,ystart,w,w);
}

color getAverageColor(PImage img,int xstart,int ystart,int xend,int yend,int w,int h) {
  int colorR = 0;
  int colorG = 0;
  int colorB = 0;

  img.loadPixels();

  int pixelCount=0;
  for (int x = xstart; x < xend; x++ ) {
    for (int y = ystart; y < yend; y++ ) {
      int loc = x + y*img.width;
      color col =  img.pixels[loc];

      colorR+= (int)red(col);
      colorG+= (int)green(col);
      colorR+= (int)blue(col);
      pixelCount++;
    }
  }
  return color(colorR/pixelCount,colorG/pixelCount,colorB/pixelCount);
}