Topic 10 Conditionally Modifying Pixels The if statement - PowerPoint PPT Presentation

1 / 67
About This Presentation
Title:

Topic 10 Conditionally Modifying Pixels The if statement

Description:

Notes adapted from Introduction to Computing and Programming with ... square root of ((red1 red2)2 (green1-green2)2 (blue1 blue2)2) (red1,green1,blue1) ... – PowerPoint PPT presentation

Number of Views:43
Avg rating:3.0/5.0
Slides: 68
Provided by: barbaraja
Category:

less

Transcript and Presenter's Notes

Title: Topic 10 Conditionally Modifying Pixels The if statement


1
Topic 10Conditionally ModifyingPixelsThe if
statement
Notes adapted from Introduction to Computing and
Programming with Java A Multimedia Approach by
M. Guzdial and B. Ericson, andinstructor
materials prepared by B. Ericson.
2
Learning Goals
  • To understand at a conceptual and practical level
  • How to use simple conditionals
  • How to use complex conditionals
  • Picture manipulation using conditionals
  • Remove red-eye
  • Edge detection
  • Sepia toning
  • Posterizing
  • Chromakey

3
Making Decisions
  • Computer programs often have to make decisions
  • Taking different actions depending on some
    condition
  • Examples
  • If the amount you want to withdraw is less than
    your bank balance, you are allowed to make the
    withdrawal, otherwise you are not
  • If a number is negative, you cannot take its
    square root

4
Making Decisions
  • More examples
  • If a turtle is too close to the edge of its
    world, it cannot move forward the specified
    distance
  • If a red value for a pixel is already 255, cant
    increase it
  • Making decisions in high-level programming
    languages is called conditional execution and is
    done using the if statement and if-else statement

5
If Statement
  • A statement or block of statements is executed
    only if some condition is true
  • If the condition is false, execution falls
    through to the next statement following the if
    statement

false
if (condition)
true
Statement or block
Next statement
6
If Statement Syntax
  • We may want a single statement to be executed if
    the condition is true if (condition)
    statement
  • We may want a block of statements to be executed
    if the condition is true if (condition)
    statement statement
  • Safer to always use braces, even if a single
    statement
  • For readability, make sure you line up the braces

7
If - else Statement
  • Using an if and else, we can do one thing if the
    condition is trueor a different thing if the
    condition is false

false
if (condition)
else
true
Statement or block
Statement or block
Next statement
8
If - else Statement Syntax
  • If the condition is true, statement1 (or block of
    statements) is executed, otherwise statement2 (or
    block of statements) is executed
  • if (condition) statement1
  • else statement2
  • Example
  • int x 200, y 100
  • if (x lt y)
  • System.out.println("y is larger")
  • else
  • System.out.println("x is larger")

9
Conditional Statement Example
  • Bank withdrawal example// amount the amount
    you want to withdraw// balance your account
    balanceif (amount lt balance) balance
    balance amount System.out.println("Balance
    is " balance)
  • What happens if amount gt balance?

10
Conditional Statement Example
  • How could we let the user know that the
    withdrawal was not allowed?if (amount lt
    balance) balance balance
    amount System.out.println("New balance is "
    balance)else System.out.println("Sorry,
    you are trying to withdraw "
    amount " and your account balance is
    only " balance)

11
Using Conditions in Pictures
  • Example Comparing colors
  • Comparing one color to another
  • Checking how close one color is to another color
  • Examples Choosing which pixels to manipulate in
    a picture
  • To remove red-eye in an image
  • To do sepia-toned images
  • To posterize images
  • etc.

12
Color Distance
  • First well look at the distance between two
    points
  • Suppose we had two points (x1,y1) and (x2,y2) and
    wanted to compute the distance between them
  • We can compute this distance as
  • square root of (( x1 x2)2 (y1 y2)2)

13
Color Distance
  • Similarly, the distance between two colors can be
    computed as
  • square root of ((red1 red2)2 (green1-green2)2
    (blue1 blue2)2)

14
Color Distance
  • There is a method in the Pixel class to compute
    this color distancepublic double
    colorDistance(Color testColor)where
  • testColor is the color to compare to
  • it returns the distance between this pixel's
    color and the passed color
  • Example of invocationdouble dist
    pixelObj.colorDistance(color1)

15
Simple Color Replacement
  • Suppose we wanted to change all of the brown in
    an image to a redder brown
  • For example, to change Katies hair color in the
    KatieFancy.jpg image
  • Algorithm
  • For each pixel in the picture
  • If the pixels color is close to being brown
  • Get the current color of the pixel
  • Increase the red in this color
  • Set the color of the pixel to this new color

16
Simple Color Replacement Method
  • public void turnBrownIntoRed()
  • Color brown new Color(42,25,15)
  • Pixel pixelObj null
  • for (int x 0 x lt this.getWidth() x)
  • for (int y 0 y lt this.getHeight() y)
  • pixelObj this.getPixel(x,y)
  • // check if distance to brown is close enough
    to adjust
  • if (pixelObj.colorDistance(brown) lt
    50.0)
  • pixelObj.setColor(new
    Color(pixelObj.getRed() 2,
  • pixelObj.getGreen(),
    pixelObj.getBlue()))

17
Simple Color Replacement Results
Before (left) and after (right) calling the
turnBrownIntoRed() methodon KatieFancy.jpg
18
Simple Color Replacement
  • This method worked, but recolored the whole image
    and not just Katies hair!
  • How can we change this method to just modify a
    rectangle of the image that contains Katies
    head?
  • How can we generalize this method to take in the
    position of this rectangle as parameters, as well
    as the distance value used as a threshold?
  • Starting from this concept, we can start doing
    fairly sophisticated operations

19
Removing Red Eye
  • Red eye is when the flash from the camera is
    reflected from the subjects eyes
  • We want to change the red color in the eyes to
    another color
  • But not change the red of her dress

20
Red Eye Removal
  • The algorithm for red eye removal is very much
    like the one for changing brown hair to red
  • What is it?
  • Method for removing red eye will have as
    parameters
  • Position of rectangle around eyes
  • New eye color
  • The distance from red can be determined
    experimentally, e.g. 167

21
Red Eye Removal Method
  • public void removeRedEye(int startX, int startY,
    int endX, int endY, Color newColor)
  • Pixel pixelObj null
  • // loop through the pixels in the rectangle
    defined by// startX, startY and endX, endY
  • for (int x startX x lt endX x)
  • for (int y startY y lt endY y)
  • // get the current pixel
  • pixelObj getPixel(x,y)
  • // if the color is near red then change it
  • if (pixelObj.colorDistance(Color.red) lt
    167)
  • pixelObj.setColor(newColor)

22
Testing removeRedEye
  • import java.awt.
  • String file FileChooser.getMediaPath(
    "jenny-red.jpg")
  • Picture p new Picture(file)
  • p.explore()
  • p.removeRedEye(109,91,202,107, Color.black)
  • p.explore()

23
Edge Detection
  • Edge detection is a research field within image
    processing and computer vision
  • in particular within the area of feature
    extraction
  • Edge detection is used to mark adjacent parts of
    an image that have high contrast
  • This gives visual clues that can help the
    recognition process
  • An edge may be regarded as a boundary between two
    dissimilar regions in an image

24
Edge Detection
  • Applications of Edge Detection
  • Medical
  • Detect thin blood vessels
  • Analyzing satellite images
  • Assume two images taken on Monday and Tuesday
  • Tuesdays image has a convoy of trucks, which
    provides a contrast with the landscape
  • Analysts may conclude that something is being
    moved

25
Edge Detection
  • The basic premise is to find the areas of high
    contrast and turn pixels in this area black
  • All other pixels are turned white
  • This is a simple form of edge detection,
    resulting in a picture that resembles a pencil
    sketch

26
Edge Detection Algorithm
  • To find areas of high contrast
  • Loop from y 0 to y lt (height 1)
  • Loop from x 0 to x lt width
  • Get the pixel at x and y (top pixel)
  • Get the pixel at x and (y 1) (bottom pixel)
  • Get the average of the top pixels color values
  • Get the average of the bottom pixels color
    values
  • If the absolute value of the difference between
    the averages is over some limit (parameter)
  • Turn the pixel black
  • Otherwise turn the pixel white

27
Conditional with Two Options
  • We now have a conditional with 2 options
  • Make the pixel be black
  • Or, make the pixel be white
  • So, we use an if-else statement

28
Edge Detection Method
  • public void edgeDetection(double limit)
  • Pixel topPixel null
  • Pixel bottomPixel null
  • double topAverage 0.0
  • double bottomAverage 0.0
  • // loop through y values from 0 to lt height
    1
  • // (since we are comparing to the pixel below)
  • for (int y 0 y lt this.getHeight() - 1
    y)
  • // loop through x values from 0 to lt width
  • for (int x 0 x lt this.getWidth() x)

29
Edge Detection Method (contd)
  • // get top and bottom pixels and their
    color averages topPixel this.getPixel(x,y)
  • bottomPixel this.getPixel(x,y1)
  • topAverage topPixel.getAverage()
  • bottomAverage bottomPixel.getAverage()
  • // check to see whether we have enough
    contrast or not // and update color to black
    or white accordingly
  • if (Math.abs(topAverage - bottomAverage)
    lt limit)
  • topPixel.setColor(Color.WHITE)
  • else topPixel.setColor(Color.BLACK)

30
Color Average
  • The Pixel class has a methodgetAverage()that
    returns the average of the red, green, and blue
    color values as a double
  • Example if a pixel has red, green, blue values
    100, 150, 25 respectively, then the color average
    for that pixel is 91.666

31
Testing Edge Detection
  • String file
  • FileChooser.getMediaPath("butterfly1.jpg")
  • Picture p new Picture(file)
  • p.explore()
  • p.edgeDetection(10)
  • p.explore()

32
Sepia-Toned Pictures
  • They have a yellowish tint, used to make things
    look old and/or western

33
Sepia-Toned Algorithm
  • First make the picture grayscale
  • Change the darkest grays (shadows) to be even
    darker
  • Make the middle grays a brown color
  • By reducing the blue
  • Make the lightest grays (highlights) a bit yellow
  • By increasing red and green
  • Or decreasing blue (less than before though)
  • We now have more than 2 possibilities, so we need
    to use multiple if statements

34
Using Multiple If Statements for gt2 Options
  • Suppose we are doing different things based on a
    set of ranges, forexample
  • 0 lt x lt 5
  • 5 lt x lt 10
  • 10 lt x
  • How many if statements will always be executed
    here (i.e. how many comparisons?)
  • if (0 lt x x lt 5)
  • statement or block
  • if (5 lt x x lt 10)
  • statement or block
  • if (10 lt x)
  • statement or block

35
Using else if for gt 2 Options
  • Or, we can use several if-else statements
  • You dont need to check if x gt 5, since the
    first if block would have been executed if it was
    lt 5
  • What is the minimum number of comparisons that
    may be made here? the maximum?
  • if (0 lt x x lt 5)
  • statement or block
  • else if (x lt 10)
  • statement or block
  • else // what must x be?
  • statement or block

36
Sepia-Toned Method
  • public void sepiaTint()
  • Pixel pixelObj null
  • double redValue 0
  • double greenValue 0
  • double blueValue 0
  • // first change the current picture to
    grayscale
  • this.grayscale()// loop through the pixels
  • for (int x 0 x lt this.getWidth() x)
  • for (int y 0 y lt this.getHeight()
    y)
  • // get the current pixel and its color
    values
  • pixelObj this.getPixel(x,y)
  • redValue pixelObj.getRed()
  • greenValue pixelObj.getGreen()
  • blueValue pixelObj.getBlue()

37
Sepia-Toned Method (continued)
  • // tint the shadows darker
  • if (redValue lt 60)
  • redValue redValue 0.9
  • greenValue greenValue 0.9
  • blueValue blueValue 0.9
  • // tint the midtones a light brown by
    reducing the blue
  • else if (redValue lt 190)
  • blueValue blueValue 0.8
  • // tint the highlights a light yellow by
    reducing the blue
  • else
  • blueValue blueValue 0.9

38
Sepia-Toned Method (continued)
  • // set the colors
  • pixelObj.setRed((int) redValue)
  • pixelObj.setGreen((int) greenValue)
  • pixelObj.setBlue((int) blueValue)

39
Testing the sepiaTint Method
  • String file FileChooser.getMediaPath("gorge.jpg"
    )
  • Picture p new Picture(file)
  • p.explore()
  • p.sepiaTint()
  • p.explore()

40
Posterizing a Picture
  • Posterizing is the process of reducing the number
    of different colors in an image

41
Posterizing a Picture
  • How can we do this?
  • Set all color values in a range to one value(the
    midpoint of the range)
  • For example use 4 ranges
  • Set values 0 - 63 to 31
  • Set values 64 - 127 to 95
  • Set values 128 - 191 to159
  • Set values 192 - 255 to 223
  • So, we end up with fewer colors

42
Posterize Algorithm
  • Loop through all the pixels in an image
  • Get the red value for the pixel
  • Find the range to which it belongs and set the
    new red value
  • Get the green value for the pixel
  • Find the range to which it belongs and set the
    new green value
  • Get the blue value for the pixel
  • Find the range to which it belongs and set the
    new blue value

43
Posterize Method
  • public void posterize()
  • Pixel pixelObj null
  • int redValue 0
  • int greenValue 0
  • int blueValue 0
  • // loop through the pixels in the image
  • for (int x 0 x lt this.getWidth() x)
  • for (int y 0 y lt this.getHeight() y)
  • // get the current pixel and its color
    values
  • pixelObj this.getPixel(x,y)
  • redValue pixelObj.getRed()
  • greenValue pixelObj.getGreen()
  • blueValue pixelObj.getBlue()

44
Posterize Method (continued)
  • // check for red range and change red
    value
  • if (redValue lt 64)
  • redValue 31
  • else if (redValue lt 128)
  • redValue 95
  • else if (redValue lt 192)
  • redValue 159
  • else
  • redValue 223

45
Posterize Method (continued)
  • // check for green range and change green
    value
  • if (greenValue lt 64)
  • greenValue 31
  • else if (greenValue lt 128)
  • greenValue 95
  • else if (greenValue lt 192)
  • greenValue 159
  • else
  • greenValue 223
  • // check for blue range and change
    blue value
  • if (blueValue lt 64)
  • blueValue 31

46
Posterize Method (continued)
  • else if (blueValue lt 128)
  • blueValue 95
  • else if (blueValue lt 192)
  • blueValue 159
  • else
  • blueValue 223
  • // set the new colors
  • pixelObj.setRed(redValue)
  • pixelObj.setGreen(greenValue)
  • pixelObj.setBlue(blueValue)

47
Testing the posterize Method
  • Test the posterize() method with tammy.jpg

48
Posterize Exercise
  • Generalize our posterize() method to take an
    integer parameter that specifies the number of
    levels (ranges) to posterize the picture
    topublic void posterize (int numLevels)
  • Your method will need to determine the range for
    each level, based on the number of levels passed
    in as the parameter

49
Dangling Else Problem
  • Consider this example if (x gt 0) if (x lt
    100) System.out.println(one
    ) else System.out.println(two)
  • Suppose x has the value 2. What do you think
    will be printed?

50
Dangling Else Problem
  • The rule is that an else goes with the closest if
  • Why did the indentation not make a difference?
  • Now what if we had wanted to group the else with
    the first if ? Use braces
  • if (x gt 0) if (x lt 100) System.out.println(
    one ) else System.out.println(two)

51
Blurring
  • We can blur or smudgean image by setting
    thecolor of a pixel to be theaverage of the
    colors ofthe surrounding pixels

52
Blurring
  • When averaging surrounding pixel colors, we must
    be careful not to go outside the two dimensional
    array of pixels for the picture
  • Otherwise, we get an exceptionjava.lang.ArrayInd
    exOutOfBoundsException
  • So, we need to make sure our array indices do not
    ever go less than 0 or outside the width or
    height of the image
  • In other words, we need to make sure our array
    indices are gt 0 and lt the width and height

53
Using the Operator
  • We need to make sure that
  • the x index is gt 0 and lt the widthand
  • the y index is gt0 and lt the height
  • So, we will use the and operator to join all
    four conditions

54
Simple Blur Method
  • public void blur(int numPixels)
  • Pixel pixel null
  • Pixel samplePixel null
  • int redValue 0
  • int greenValue 0
  • int blueValue 0
  • int count 0
  • // loop through the pixels in the image
  • for (int x 0 x lt this.getWidth() x)
  • for (int y 0 y lt this.getHeight() y)

55
Simple Blur Method (continued)
  • // get the current pixel and reset count
    and color values
  • pixel this.getPixel(x,y)
  • count 0
  • redValue 0
  • greenValue 0
  • blueValue 0
  • // loop through numPixels before and
    after the current // pixel in both the x and
    y directions
  • for (int xSample x - numPixels
    xSample lt x numPixels xSample)
    for (int ySample y - numPixels
    ySample lt y numPixels ySample)

56
Simple Blur Method (continued)
  • // check that we are in the
    acceptable range // to get sample pixel
    to include in our average if ((xSample gt 0)
    (xSample lt this.getWidth())
    (ySample gt 0) (ySample lt this.getHeight()))
  • // get sample position from this location
    and // include its color values in our
    average samplePixel this.getPixel(xSamp
    le, ySample) redValue redValue
    samplePixel.getRed() greenValue
    greenValue
    samplePixel.getGreen() blueValue
    blueValue samplePixel.getBlue() count
    count 1 // end of ySample
    loop
  • // end of xSample loop

57
Simple Blur Method (continued)
  • // now use the average of the color from
    surrounding // pixels as the color for this
    pixel Color newColor new
    Color(redValue/count,
  • greenValue/count,
  • blueValue/count)
  • pixel.setColor(newColor)

58
Simple Blur Method
  • What happens if one of the surrounding pixels
    goes outside the image?

59
Simple Blur Results
  • The blur() method with parameter 2 applied to the
    image in flower1.jpg
  • (shown here after first using the scaleUp()
    method to blow up the flower image)

60
Chromakey
  • The weather announcers on TV are not really
    standing in front of a changing weather map
  • They are in front of a solid colour background
  • blue or green (but usually blue its better
    for skintones)
  • So how do the weather map images appear behind
    them?
  • If a pixels color is blue, replace it with color
    of corresponding pixel from new background image
  • Also used for special effects in TV and movies

61
Chromakey Blue Screen
  • Here just a blue sheet was used
  • Professionally, you need an evenly lit, bright,
    pure blue background
  • With nothing blue in the part of the image you
    want to keep

62
Chromakey New Background
  • Man on the moon!

63
Chromakey Algorithm
  • Our method will be invoked on an image with a
    blue screen
  • The blue will be replaced as a background by
    another image
  • This new background image will be passed in as a
    parameter
  • Algorithm
  • Loop through all the pixels
  • If the pixel color is blue(we can use red
    value green value lt blue value)
  • Replace the pixel color with the color from the
    pixel at the same location in the new background
    picture

64
Chromakey Method
  • public void chromakey(Picture newBackground)
  • Pixel currPixel null
  • Pixel newPixel null
  • // loop through the columns
  • for (int x0 xltthis.getWidth() x)
  • // loop through the rows
  • for (int y0 yltthis.getHeight() y)
  • // get the current pixel
  • currPixel this.getPixel(x,y)

65
Chromakey Method (continued)
  • / if the color of the pixel at this
    location is mostly blue
  • (blue value greater than red and
    green combined),
  • then use new background color at this
    pixel
  • /
  • if (currPixel.getRed()
    currPixel.getGreen() lt

  • currPixel.getBlue())
  • newPixel newBackground.getPixel(x,y)
  • currPixel.setColor(newPixel.getColor())
  • //Note could use color distances to
    determine "blue"

66
Testing chromakey
  • Picture markP new Picture(FileChooser.getMediaPa
    th("blue-mark.jpg"))
  • Picture newBackground new Picture(FileChooser.ge
    tMediaPath("moon-surface.jpg"))
  • markP.chromakey(newBackground)
  • markP.show()
  • We have a powerfulpicture manipulationwith a
    simple ifstatement!

67
Java Concepts in this Section
  • If statements
  • If else statements
  • With 2 options
  • With more than 2 options
  • Dangling else
  • Using to join conditions
Write a Comment
User Comments (0)
About PowerShow.com