Theme 1: Loop bulk operation - e.g. for-loop
- Loop body code runs again and again
Theme 2: Logic test true/false - e.g. if-statement (this section)
- Run some code only if a test is true
Our use of loops thus far have allowed us to write a little bit of code which is run for many data points. That's one big theme in computer code. The if-statement, the topic of this section, will add a second theme: the ability to write a true/false test to control if a bit of code runs or not. Combined with the loop, the if-statement will greatly expand what we can do with code.
Pixels X/Y functions: pixel.getX() and pixel.getY()
These retrieve the X and Y values of the pixel
Analogous to pixel.getRed()
There are also image.getWidth() and image.getHeight()
e.g. image.getWidth() on the stop sign image yields 500
For now, you may type in literal numbers like 500
If-Statement Demo
The if-statement has a true/false test which controls if some code is run or not. Here is an example if-statement shown inside a for-loop with the "stop.jpg" image.
image-logic-1
1. if (pixel.getX() < 100) { - "test" inside parenthesis
2. Curly braces around body code after the test { .. } (indented) - just like for loop!
How works: the loop hits every x,y. Only some x,y pass the test (like a filter)
For now just using < (less than) or > (greater than) in test
Experiment 1: try pixel.getX() < 150 300 10
Experiment 2: now try pixel.getY() < 100 200
The Flip
Change < to >, .e.g. (pixel.getX() > 100)
Get the opposite (well, very close to the opposite)
Flip Diagram
If-Statement - You Try It
Figure out code for the following
stop.jpg is 500 pixels wide, 375 pixel high
a. Set approximately the left 2/3's of the image to pure blue, just enough so none of the stop sign is visible
b. Set a vertical stripe 20 pixels wide at the far right to blue
c. Set a horizontal stripe 20 pixels high across the top of the image to black
d. Set the flip of (c) to black, i.e. all except the top horizontal stripe to black
image-logic-2
Solution code
// a. if (pixel.getX() < 355) {
// b. if (pixel.getX() > 480) {
// c. if (pixel.getY() < 20) {
// d. if (pixel.getY() <> 20) {
image = new SimpleImage("stop.jpg");
for (pixel: image) {
if (pixel.getX() < 355) {
pixel.setRed(0);
pixel.setGreen(0);
pixel.setBlue(255); // 0 here for black
}
}
print(image);
Using image.getWidth() Expressions (optional)
The "stop.jpg" image is 500 pixels wide
Therefore to paint the left half, the test uses 250, as below
The code uses 250 since that is 500/2
Instead:
- instead of 250 type in below image.getWidth()/2 - i.e. an expression that computes the midpoint based on the image width
- change it to work on "poppy.jpg" instead of "stop.jpg"
- it just works!
- This is analogous to the examples from expressions last class.
This technique is not required on these exercises, optional