Algorithm for RGB to HSV and HSV to RGB Conversion in Range 0-255
A color space conversion algorithm is presented for transforming RGB color values to HSV and vice versa, maintaining the range of 0 to 255 in both color spaces. Here's how it operates:
RGB to HSV Conversion (rgb2hsv)
To convert RGB values (r, g, b) to HSV (h, s, v):
- Determine the minimum and maximum values among r, g, and b.
- Calculate the value component (v) as the maximum value.
- Calculate the saturation component (s) as the proportion of (v - minimum value) to v.
-
Determine the hue component (h):
- If r is maximum, h is calculated as (g - b) / (v - minimum value).
- If g is maximum, h is 2.0 (b - r) / (v - minimum value).
- If b is maximum, h is 4.0 (r - g) / (v - minimum value).
- Convert the h angle to degrees.
- If h is negative, add 360 degrees.
HSV to RGB Conversion (hsv2rgb)
To convert HSV values (h, s, v) to RGB (r, g, b):
- If s is zero, set r, g, and b to v.
- Otherwise, calculate the hue angle fraction (hh) and the floor (i) of hh.
- Calculate the values p=v⋅(1−s), q=v⋅(1−s⋅(1−hh)), and t=v⋅(1−s⋅hh).
-
Based on i, assign values to r, g, and b:
- Case 0: r=v, g=t, b=p
- Case 1: r=q, g=v, b=p
- Case 2: r=p, g=v, b=t
- Case 3: r=p, g=q, b=v
- Case 4: r=t, g=p, b=v
- Case 5: r=v, g=p, b=q
These functions enable efficient and accurate conversion between RGB and HSV color spaces, which is vital for applications involving color manipulation and image processing.
The above is the detailed content of How to Convert RGB to HSV and HSV to RGB Values within a 0-255 Range?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn