Thursday 7 May 2009

Sine in action - part 3

Drawing with pixels

In section 21 we saw that individual pixels could be referred to by using their position in Cartesian coordinates. This technique can be used to set the colour of individual pixels in an image; which is how we colour points in relation to our sine function in our final program.

The steps needed are:
  1. Create a PImage object img.
  2. PImage img = createImage(300,200,RGB);

  3. Set the colour of one or more pixels. The pixel at the point (x,y)of the image object can be set using the line:
    img.set(x,y,aColor);

  4. Display the image after all points have been set using the line:
    image(img,0,0,width,height);
For example we use this method to plot a sine function by setting the pixel at point (x, f(x)) to be a particular colour; where f(x) is our sine function.

As we saw earlier the basic form of the sine function is

f(θ) = amplitude * sin( frequency * θ)

We have chosen to scale f(θ) so that it is calculated between 0 and 2 π over the width of the image, such that θ at x is defined as follows.

θ = ( 2 π /img.width ) * x

This gives us

f(x) = amplitude * sin( frequency * ( 2 π /img.width ) * x )


We can draw this function by colouring the pixels at white, as follows

size(600, 300);
//create the image
PImage img;
img = createImage(600,300,RGB);

//set variables for sine function
int y = 0;
float theta = 0;
float dTheta = TWO_PI / img.width;
float amplitude = img.height/2 ;
float damping = 0.994;
float position = img.height/2;
float frequency = 99;

//set colour of points
for (int x=0; x <= img.width; x++){
y = round(position + amplitude*sin(frequency*theta));
color c = color(255);
img.set(x,y,c);
theta += dTheta;
amplitude *= damping;
}
// display the results
image(img,0,0,width,height);



Figure 4 sine function plotted with pixels

In this example we have chosen a high frequency of 99. It is this choice of frequency that gives us the rather intricate distribution we can see in Figure 4. Although in this image it appears we are plotting four different strands, in fact there is only one and the distance between the plotted points at out chosen frequency gives us this effect.

No comments: