Learning Processing #3 – Image Processing

This week’s Processing workshop covered using images and processing them into pixels.

PImage img1;
PImage img2;
PImage img3;
PImage img4;

void setup(){
  img1 = loadImage("goat1.jpg");
  img2 = loadImage("goat2.jpg");
  img3 = loadImage("goat3.jpg");
  img4 = loadImage("goat4.jpg");
  size(img3.width,img3.height);
  background(800,600);
}

int n=5;
int loc;

void draw(){
  img3.loadPixels();
    for (int y=0; y<height; y=y+n){
      for (int x=0; x<width; x=x+n){
       loc= x + (y*width);
       noStroke();
       fill(img3.pixels[loc]);
      rect(x+random(-5,5),y+random(-5,5),n*0.8,n*0.8);
      }
    }
    imageChanger();
    if (mousePressed && mouseButton==RIGHT || keyPressed){
    doSomeText();
    } else {}
}

void imageChanger(){
  if (mousePressed && mouseButton==LEFT || keyPressed) {
    img3 = loadImage("goat3.jpg");
  }else{ img3=loadImage("goat2.jpg");
}
}

void doSomeText(){
  textSize(35);
 fill(255,0,0);
 text("I'm a goat",150,150);
}

Above is the code used. Several images are loaded at the start of the sketch using the PImage function, and are defined as “img1-4” for later use. In the draw section, from lines 19-26, the loaded image is processed into a mosaic. This is done with “loadPixels”, and a couple of nested for loops. These function like in the earlier workshop, creating a grid of rectangles, however in this case the fill is taken from img3.pixels[loc], which locates a pixel and takes its color value – putting it in the fill. The grid of rectangles are then made sized up so they aren’t 1px wide and high, creating the mosaic effect. Another simple effect is the use of random values in the x and y coordinates for each rectangle, giving them +random(5,-5) to both x and y makes them move around randomly from frame to frame, within a boundary of 5 pixels either way (the size of the rectangles).

A couple of functions are then used for interaction – void imageChanger (lines 34-38) is a function that changes the picture that is loaded to a different one when the mouse is pressed. The rectangles are then drawn again, giving a similar effect to previously but with a different picture.

These are simple ways to load images into processing and then turn their pixel values into usable integers, which could prove useful for creating visual effects based on images in the future.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s