CDA - Processing Images Lesson
Processing Images
So we can load and display an image, but what if we want to read the pixels in the image and change the colors? Processing has built in functions that will change the appearance of images very easily.
The filter() function filters the display window using a preset filter or with a custom shader (is anyone thinking "That's abstraction!")
PImage img;
int width = 400;
int height = 400;
void setup()
{
img = loadImage("eye.jpg");
size(img.width, img.height);
image(img, 0, 0);
filter(GRAY);
}
void draw()
{
}
Using the Pixels[] Array to Modify Images
We are familiar with the idea of each pixel on the screen having an X and Y position in a two dimensional window. However, the pixels[] has only one dimension, storing color values in a linear sequence. The rows of the 2D array are laid out to form a 1D array and are stored in a single pixel array. Now you can use the pixels[] array of the PImage class to access the pixel colors.
There are functions in the PImage class that will get the red, green, and blue values from the pixel. The value is always returned as a float, so be careful not to assign it to an int value.
red(float value) Extracts the red value from a pixel
green(float value) Extracts the green value from a pixel
blue(float value) Extracts the blue value from a pixel
These functions can be used with the pixels[] array to modify an image. If you multiply the image by 2, the image will become lighter. If each value is divided by 2, the image will become darker.
Using a loop makes it easy to change every pixel in the image. Since the pixels[] is a one-dimensional array, a loop is necessary to modify every pixel in the image.
The program below shows how to load an image as a background.
IMPORTANT: When you use an image as the background, the size of the frame and the image must be the same size. In the example below, the image is 468 x 311 so the frame size is 468 x 311
PImage img;
public void setup() {
size(468,311);
img = loadImage("bird.png");
}
public void draw() {
background(img);
img.updatePixels();
}
The program below uses a for loop to access the pixels in the image. It then captures the red, green and blue values at the current pixel index. Remember, the value is always returned as a float. The blue value is replaced with the red value in the picture and then updated producing the effect shown.
img.pixels[i] = color(r, g, r);
PImage img;
public void setup() {
size(468,311);
img = loadImage("bird.jpg");
for(int i = 0; i < img.pixels.length; i++)
{
color c = img.pixels[i];
float r = red(c);
float g = green(c);
float b = blue(c);
img.pixels[i] = color(r, g, r);
}
img.updatePixels();
image(img, 0, 0, width, height);
}
public void draw()
{
}
Pixel Array Video
Watch the Pixel Array video below.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION