Home > Backend Development > C++ > How to Convert RGB to HSV and HSV to RGB Values within a 0-255 Range?

How to Convert RGB to HSV and HSV to RGB Values within a 0-255 Range?

Linda Hamilton
Release: 2024-12-10 10:20:15
Original
1014 people have browsed it

How to Convert RGB to HSV and HSV to RGB Values within a 0-255 Range?

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):

  1. Determine the minimum and maximum values among r, g, and b.
  2. Calculate the value component (v) as the maximum value.
  3. Calculate the saturation component (s) as the proportion of (v - minimum value) to v.
  4. 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).
  5. Convert the h angle to degrees.
  6. If h is negative, add 360 degrees.

HSV to RGB Conversion (hsv2rgb)

To convert HSV values (h, s, v) to RGB (r, g, b):

  1. If s is zero, set r, g, and b to v.
  2. Otherwise, calculate the hue angle fraction (hh) and the floor (i) of hh.
  3. Calculate the values p=v⋅(1−s), q=v⋅(1−s⋅(1−hh)), and t=v⋅(1−s⋅hh).
  4. 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template