Hi!
I’m working on an application that assigns color names based on the hue of a pixel in an image. The method I am currently using is inelegant:
- Create a String array that holds the names of colors that I want to use.
- Get the hue at pixels[loc].
- Use a billion “if” statements to check which range the pixel’s hue falls into.
- Print the color name (to console, for now).
Here is an example of the code:
if ( 0.0 <= hue && hue < 30.0) {println(colorNameArray[0]);} // Red
else if ( 30.0 <= hue && hue < 60.0) {println(colorNameArray[1]);} // Orange
else if ( 60.0 <= hue && hue < 90.0) {println(colorNameArray[2]);} // Yellow
Is there a neater way to do this? Thank you!
1 Like
Maybe. Is each section 30 hue-units big? If so, just divide:
println(colorNameArray[int(hue/30)]);
If they’re not all 30, then you’ll have to put their amounts into an array. Then you can loop over it:
int[] bounds = {0, 30, 40, 50, 90, 120};
for( int i = 0; i < bounds.length-1; i++){
if( bounds[i] <= hue && hue < bounds[i+1]){
println(colorNameArray[i]);
}
}
2 Likes
Perfect, exactly what I was looking for.
Thank you very much!
You might also be interested in
Java also has built-in names for a small palette of colors:
https://docs.oracle.com/javase/8/docs/api/java/awt/Color.html
so you could iterate over those and compare if you didn’t want to provide your own.
https://www.quora.com/Java-How-to-get-the-name-of-colors-in-Java-from-Hex-or-RGB-values
2 Likes
These were great reads, I learned something new and feel closer to solving my problem.
Thank you very much for your reply and your time!
1 Like