CS 101

If Statements

Plan for Today

  • Last time, we learned about for loops, a way to repeat operations many times.
  • Now, we're going to learn how to conditionally or sometimes apply those operations using if statements. We'll also implement a new filter.

If Statements

  • For loops: always apply the operation to every pixel
  • What if we only want to apply the operation to some pixels?
  • Parts of an if statement:
    • condition
    • body

 

Conditions

  • Must be either true or false
  • Generally use >, <, >=, <=, == (equals), or != (not equal)
  • Only pixels that "pass the test" will have the operation executed
  • Other code to know:
    • pixel.getX(), pixel.getY()
    • img.getWidth(), img.getHeight()
  • General idea: based on some property of the pixel, we'll perform an operation on it.
    • Color
    • Location
    • Number of neighbors

Fancy Diagonals

Write code to make a purple diagonal line running bottom left to top right.

 

Making a border

How can we make a one-pixel thick green border around an image?

 

Fancier Diagonals

  • What if we want to do something if the test passes and something else if the test fails?
    • Solution: use else
  • Write code to make a purple diagonal line running bottom left to top right, and color the rest of the pixels green.

 

Combining Conditionals

  • What if you want multiple tests at once?
  • and (written as &&) means both parts have to be true to pass
  • or (written as ||) means only one of the two tests have to pass
  • How can we color the top-right quadrant purple?

 

Edge Detection

figure
  • Idea: Want to make a black-and-white image where the "edges" in the original image are now black
  • Edge: A pixel is sufficiently different from at least one of its neighbors:
    • pixel.isDifferentFrom(pixel2, threshold);
  • What building blocks can help us? What does this filter have in common with the blur filter from Tuesday?

Writing Edge Detection


 

Recap

Today, we learned how to selectively apply code using if statements. Next time, we'll do more advanced green screen techniques, and you'll edit your own images.