Week 10 -- Digital Image Processing contd. . .
back to syllabusprevious page
A Simpler Blur
There was some confusion last week regarding the "convolution" example. Below is a simpler version of a neighborhood pixel processing example. In the following example, for every pixel (x,y) that we want to draw on the screen, we take the average of a group of pixels (in a 3x3 matrix) from our source image.
In the example, we do our usual nested loop where we walk through every xy coordinate in our image. For each xy coordinate, we call our own "blur" function. The blur functions calculates the average RGB color for every surrounding pixel and sends it back to the calling area. It is this process of averaging pixels that causes the image to blur.
BImage a;
BFont fontA;
void setup()
{
size(320, 240);
a = loadImage("sunflower.jpg");
fontA = loadFont("Univers55.vlw.gz");
}
void loop()
{
//place image as background
image(a,0,0);
textFont(fontA, 24);
text("click mouse to apply blur", 10, 230);
//if the mouse is clicked let's go through and process each pixel
if (mousePressed) {
//begin our loop for every pixel
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++ ) {
//call our own blur function with 3 parameters, our xy coordinates and the source image
//in return, we'll get a color back
color c = blur(x,y,a);
int loc = x + y*a.width;
pixels[loc] = c;
}
}
}
}
color blur(int x, int y, BImage a)
{
//our new color will be stored here
float sumR = 0.0;
float sumG = 0.0;
float sumB = 0.0;
//loop to check all neighboring 3x3 pixels
for (int i =-1; i<2; i++){
for (int j=-1; j<2; j++){
//what pixel are we looking at
int xloc = x+i;
int yloc = y+j;
int loc = xloc + a.width*yloc;
//make sure we haven't walked off our image
loc = constrain(loc,0,a.pixels.length-1);
//add up all colors
sumB += blue(a.pixels[loc]);
sumG += green(a.pixels[loc]);
sumR += red(a.pixels[loc]);
}
}
//divide by 9 to get the average color
sumR = sumR / 9.0f;
sumG = sumG / 9.0f;
sumB = sumB / 9.0f;
//make sure RGB is withing range
sumR = constrain(sumR,0,255);
sumG = constrain(sumG,0,255);
sumB = constrain(sumB,0,255);
//return the resulting color
return color(sumR,sumG,sumB);
}
back to syllabus