PIXELBANKv9.1.0
Menu

RGB to HSV Conversion

Given a single RGB pixel with values in [0, 255], convert it to HSV color space.

Algorithm:

  1. Normalize R, G, B to [0, 1] by dividing by 255
  2. Compute Cmax=max⁡(R′,G′,B′)C_{max} = \max(R', G', B'), Cmin=min⁡(R′,G′,B′)C_{min} = \min(R', G', B'), Δ=Cmax−Cmin\Delta = C_{max} - C_{min}
  3. Hue (0-360 degrees):
    • If Δ=0\Delta = 0: H=0H = 0
    • If Cmax=R′C_{max} = R': H=60×(((G′−B′)/Δ)mod  6)H = 60 \times (((G' - B') / \Delta) \mod 6)
    • If Cmax=G′C_{max} = G': H=60×(((B′−R′)/Δ)+2)H = 60 \times (((B' - R') / \Delta) + 2)
    • If Cmax=B′C_{max} = B': H=60×(((R′−G′)/Δ)+4)H = 60 \times (((R' - G') / \Delta) + 4)
  4. Saturation (0-1): S=0S = 0 if Cmax=0C_{max} = 0, else Δ/Cmax\Delta / C_{max}
  5. Value (0-1): V=CmaxV = C_{max}

Return [H,S,V][H, S, V] with H rounded to 2 decimal places, S and V rounded to 4 decimal places.

Example:

Input:
pixel = [255, 0, 0]
Output:
[0.0, 1.0, 1.0]
Reasoning:
  • First, we normalize the RGB values to [0, 1] by dividing by 255: R′=255255=1R' = \frac{255}{255} = 1, G′=0255=0G' = \frac{0}{255} = 0, B′=0255=0B' = \frac{0}{255} = 0
  • Then, we compute Cmax=max⁡(R′,G′,B′)=1C_{max} = \max(R', G', B') = 1, Cmin=min⁡(R′,G′,B′)=0C_{min} = \min(R', G', B') = 0, and Δ=Cmax−Cmin=1−0=1\Delta = C_{max} - C_{min} = 1 - 0 = 1
  • Since Cmax=R′C_{max} = R', we calculate the hue: H=60×(((G′−B′)/Δ)mod  6)=60×((0−0)/1)mod  6=0H = 60 \times (((G' - B') / \Delta) \mod 6) = 60 \times ((0 - 0) / 1) \mod 6 = 0
  • The saturation and value are calculated as S=ΔCmax=11=1S = \frac{\Delta}{C_{max}} = \frac{1}{1} = 1 and V=Cmax=1V = C_{max} = 1, resulting in the output [H,S,V]=[0.0,1.0,1.0][H, S, V] = [0.0, 1.0, 1.0]

Constraints:

  • Pixel is [R, G, B] with integer values in [0, 255]
  • H in [0, 360), S in [0, 1], V in [0, 1]
  • If max = 0, then H = 0 and S = 0
  • Return list [H, S, V]
solution.py

Test Results

0/0
Run code to see test results.
RGB to HSV Conversion - Medium | PixelBank