HSV separates a colour's hue from its brightness. Convert colours from RGB.
What to build
A program that converts RGB colours to hue, saturation and value.
Requirements
- Hue in degrees from 0 to below 360; saturation (hi − lo) / hi, or 0 when hi is 0; value hi / 255.
- When several channels share the largest value, use the first of red, green, blue in that order to choose the hue formula.
- Print
H S Vwith one decimal place for H and three for S and V.
Input
Line 1: N. Then N lines, each R G B with values from 0 to 255.
Output
N lines.
Constraints
N ≤ 1000.
Example
Input:
3
255 0 0
0 255 0
0 0 255
Output:
0.0 1.000 1.000
120.0 1.000 1.000
240.0 1.000 1.000
Why it works
The largest channel decides which third of the colour wheel the hue lies in, and the other two channels decide where inside it; saturation and value describe purity and brightness separately.
Examples
3 255 0 0 0 255 0 0 0 255
0.0 1.000 1.000 120.0 1.000 1.000 240.0 1.000 1.000
2 128 128 128 0 0 0
0.0 0.000 0.502 0.0 0.000 0.000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Let hi = max(R, G, B), lo = min(R, G, B) and d = hi − lo. If d is 0 the hue is 0.
Hint 2
If red is largest use 60 × (((G − B) / d) % 6); if green, 60 × ((B − R) / d + 2); otherwise 60 × ((R − G) / d + 4). Check red first when channels tie.
Solution
Show one correct solution (try it yourself first)
for _ in range(int(input())):
r, g, b = map(int, input().split())
hi, lo = max(r, g, b), min(r, g, b)
d = hi - lo
if d == 0:
h = 0.0
elif hi == r:
h = 60 * (((g - b) / d) % 6)
elif hi == g:
h = 60 * ((b - r) / d + 2)
else:
h = 60 * ((r - g) / d + 4)
s = 0.0 if hi == 0 else d / hi
print(f"{h:.1f} {s:.3f} {hi / 255:.3f}")