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
    • Green Screen
    • Edge Detection

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 make a green border and diagonal?

 

Green Screen

  • Works by replacing all the pixels of a certain color in one image with another image
    • Color depends on the original image
  • Idea: if a pixel is "close" in color to our target color, replace it with the corresponding pixel in the other image

Green Screen In Action

Green Screen Continued

  • How do we replace a pixel with another?
  • The conditional now has a new building block:
    • if(pixel1.isSimilarTo(RED, GREEN, BLUE, NUMBER))
    • The RED, GREEN, and BLUE values represent the target color
    • NUMBER is the "tolerance": bigger number be true more often. Should be between 0 and 255
    • No need to use an inequality operator; that line of code just gives us a true or false directly
yosemite.jpg paris.jpg

Writing Green Screen


 

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
  • What building blocks can help us?

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.