COS 130 Computer Programming Methodology Luminance More about
COS 130 Computer Programming Methodology Luminance
More about color or lack there of Luminance
Luminance • Used to represent color as shades of grey • The eye sees different colors with more or less intensity • Therefore we weight different colors when converting them to grey
Luminance We will use this formula to go from RGB to luminance (gray scale) red * 0. 3 + green * 0. 59 + blue * 0. 11
Luminance Formula in Java int red; int green; int blue; int gs; . . . gs = red * 0. 3 + green * 0. 59 + blue * 0. 11; What happens here? Truncate! int double Promoted to double
Casting Primitives • Tells the compiler – Just Trust Me, I know what I’m doing gs = (int) (red * 0. 3 + green * 0. 59 + blue * 0. 11); A cast (in this case to an int)
When to use • Promotion – Put a small thing into a big thing – Generally safe – Happens automatically • Casting – – Put a big thing into a small thing You must code May result in errors Example int n = (int) 2. 34
Rounding • When we truncate we would really like to round to the closest integer int num = (int)3. 999; In this example we would like num to end up as 4 not 3 So we add. 5 int num = (int) (3. 999 +. 5);
Final Version Luminance in Java gs = (int) (red * 0. 3 + green * 0. 59 + blue * 0. 11 +. 5);
What values are allowed? gs = (int) (red * 0. 3 + green * 0. 59 + blue * 0. 11 +. 5); System. out. write(gs); 0 through 255 public static int clamp(int n) { if(n < 0) return 0; if(n > 255) return 255; return n; } gs = (int) (red * 0. 3 + green * 0. 59 + blue * 0. 11 +. 5); gs = clamp(gs); System. out. write(gs);
- Slides: 10