Friday, September 4, 2026
Social icon element need JNews Essential plugin to be activated.
No Result
View All Result
Digital Currency Pulse
  • Home
  • Crypto/Coins
  • NFT
  • AI
  • Blockchain
  • Metaverse
  • Web3
  • Exchanges
  • DeFi
  • Scam Alert
  • Analysis
Crypto Marketcap
Digital Currency Pulse
  • Home
  • Crypto/Coins
  • NFT
  • AI
  • Blockchain
  • Metaverse
  • Web3
  • Exchanges
  • DeFi
  • Scam Alert
  • Analysis
No Result
View All Result
Digital Currency Pulse
No Result
View All Result

From RGB to HSV — and Back Again

May 7, 2025
in Artificial Intelligence
Reading Time: 7 mins read
A A
0

[ad_1]

A basic idea in Laptop Imaginative and prescient is knowing how photos are saved and represented. On disk, picture recordsdata are encoded in varied methods, from lossy, compressed JPEG recordsdata to lossless PNG recordsdata. When you load a picture right into a program and decode it from the respective file format, it would most definitely have an array-like construction that represents the pixels within the picture.

RGB

Every pixel accommodates some colour details about that particular level within the picture. Now the commonest strategy to symbolize this colour is within the RGB house, the place every pixel has three values: crimson, inexperienced and blue. These values describe how a lot of every colour is current and they are going to be combined additively. So for instance, a picture with all values set to zero might be black. If all three values are set to 100%, the ensuing picture might be white.

Generally the order of those colour channels may be swapped. One other frequent order is BGR, so the order is reversed. That is generally utilized in OpenCV and the default when studying or displaying photos.

Alpha Channel

Photos can even comprise details about transparency. In that case, an extra alpha channel is current (RGBA). The alpha worth signifies the opacity of every pixel: an alpha of zero means the pixel is totally clear and a worth of 100% represents a totally opaque pixel.

HSV

Now RGB(A) shouldn’t be the one strategy to symbolize colours. In truth there are lots of completely different colour fashions that symbolize colour. One of the crucial helpful fashions is the HSV mannequin. On this mannequin, every colour is represented by a hue, saturation and worth property. The hue describes the tone of colour, no matter brightness and saturation. Generally that is represented on a circle with values between 0 and 360 or 0 to 180, or just between 0 and 100%. Importantly, it’s cyclical, which means the values wrap round. The second property, the saturation describes how intense a colour tone is, so a saturation of 0 ends in grey colours. Lastly the worth property describes the brightness of the colour, so a brightness of 0% is all the time black.

Now this colour mannequin is extraordinarily useful in picture processing, because it permits us to decouple the colour tone from the saturation and brightness, which is not possible to do immediately in RGB. For instance, if you’d like a transition between two colours and hold the identical brightness throughout the full transition, this might be very advanced to realize utilizing the RGB colour mannequin, whereas within the HSV mannequin that is easy by simply interpolating the hue.

Sensible Examples

We’ll take a look at three examples of the right way to work with these colour areas in Python utilizing OpenCV. Within the first instance, we extract components of a picture which might be of a sure colour. Within the second half, we create a utility perform to transform colours between the colour areas. Lastly, within the third software, we create a steady animation between two colours with fixed brightness and saturation.

1 – Shade Masks

The purpose of this half is to discover a masks that isolates colours primarily based on their hue in a picture. Within the following image, there are completely different coloured paper items that we wish to separate.

colored paper pieces

Utilizing OpenCV, we will load the picture and convert it to the HSV colour house. By default photos are learn in BGR format, therefore we’d like the flag cv2.COLOR_BGR2HSV within the conversion:

Python”>import cv2

img_bgr = cv2.imread(“photos/notes.png”)
img_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)

Now on the HSV picture we will apply a colour filter utilizing the cv2.inRange perform to specify a decrease and higher sure for every property (hue, saturation, worth). With some experimentation I arrived on the following values for the filter:

PropertyLower BoundUpper BoundHue90110Saturation60100Value150200

masks = cv2.inRange(
src=img_hsv,
lowerb=np.array([90, 60, 150]),
upperb=np.array([110, 100, 200]),
)

The hue filter right here is constrained between 90 and 110, which corresponds to the sunshine blue paper on the backside of the picture. We additionally set a variety of the saturation and the brightness worth to get a fairly correct masks.

To indicate the outcomes, we first must convert the single-channel masks again to a BGR picture form with 3 channels. Moreover, we will additionally apply the masks to the unique picture and visualize the consequence.

mask_bgr = cv2.cvtColor(masks, cv2.COLOR_GRAY2BGR)
img_bgr_masked = cv2.bitwise_and(img_bgr, img_bgr, masks=masks)

composite = cv2.hconcat([img_bgr, mask_bgr, img_bgr_masked])
cv2.imshow(“Composite”, composite)

By altering the hue vary, we will additionally isolate different items. For instance for the purple paper, we will specify the next vary:

PropertyLower BoundUpper BoundHue160175Saturation80110Value170210

2 – Shade Conversion

Whereas OpenCV gives a helpful perform to transform full photos between colour areas, it doesn’t present an out-of-the-box resolution to transform single colours between colour areas. We are able to write a easy wrapper that creates a small 1×1 pixel picture with an enter colour, makes use of the built-in OpenCV perform to transform to a different colour house and extract the colour of this single pixel once more.

def convert_color_space(enter: tuple[int, int, int], mode: int) -> tuple[int, int, int]:
“””
Converts between colour areas

Args:
enter: A tuple representing the colour in any colour house (e.g., RGB or HSV).
mode: The conversion mode (e.g., cv2.COLOR_RGB2HSV or cv2.COLOR_HSV2RGB).

Returns:
A tuple representing the colour within the goal colour house.
“””
px_img_hsv = np.array([[input]], dtype=np.uint8)
px_img_bgr = cv2.cvtColor(px_img_hsv, mode)
b, g, r = px_img_bgr[0][0]
return int(b), int(g), int(r)

Now we will check the perform with any colour. We are able to confirm that if we convert from RGB -> HSV -> RGB again to the unique format, we get the identical values.

red_rgb = (200, 120, 0)

red_hsv = convert_color_space(red_rgb, cv2.COLOR_RGB2HSV)
red_bgr = convert_color_space(red_rgb, cv2.COLOR_RGB2BGR)
red_rgb_back = convert_color_space(red_hsv, cv2.COLOR_HSV2RGB)

print(f”{red_rgb=}”) # (200, 120, 0)
print(f”{red_hsv=}”) # (18, 255, 200)
print(f”{red_bgr=}”) # (0, 120, 200)
print(f”{red_rgb_back=}”) # (200, 120, 0)

3 – Steady Shade Transition

On this third instance, we’ll create a transition between two colours with a relentless brightness and saturation interpolation. This might be in comparison with a direct interpolation between the preliminary and remaining RGB values.

def interpolate_color_rgb(
start_rgb: tuple[int, int, int], end_rgb: tuple[int, int, int], t: float
) -> tuple[int, int, int]:
“””
Interpolates between two colours in RGB colour house.
Args:
start_rgb: The beginning colour in RGB format.
end_rgb: The ending colour in RGB format.
t: A float between 0 and 1 representing the interpolation issue.
Returns:
The interpolated colour in RGB format.
“””
return (
int(start_rgb[0] + (end_rgb[0] – start_rgb[0]) * t),
int(start_rgb[1] + (end_rgb[1] – start_rgb[1]) * t),
int(start_rgb[2] + (end_rgb[2] – start_rgb[2]) * t),
)

def interpolate_color_hsv(
start_rgb: tuple[int, int, int], end_rgb: tuple[int, int, int], t: float
) -> tuple[int, int, int]:
“””
Interpolates between two colours in HSV colour house.
Args:
start_rgb: The beginning colour in RGB format.
end_rgb: The ending colour in RGB format.
t: A float between 0 and 1 representing the interpolation issue.
Returns:
The interpolated colour in RGB format.
“””
start_hsv = convert_color_space(start_rgb, cv2.COLOR_RGB2HSV)
end_hsv = convert_color_space(end_rgb, cv2.COLOR_RGB2HSV)

hue = int(start_hsv[0] + (end_hsv[0] – start_hsv[0]) * t)
saturation = int(start_hsv[1] + (end_hsv[1] – start_hsv[1]) * t)
worth = int(start_hsv[2] + (end_hsv[2] – start_hsv[2]) * t)

return convert_color_space((hue, saturation, worth), cv2.COLOR_HSV2RGB)

Now we will write a loop to check these two interpolation strategies. To create the picture, we use the np.full technique to fill all pixels of the picture array with a specified colour. Utilizing cv2.hconcat we will mix the 2 photos horizontally into one picture. Earlier than we show them, we have to convert to the OpenCV format BGR.

def run_transition_loop(
color_start_rgb: tuple[int, int, int],
color_end_rgb: tuple[int, int, int],
fps: int,
time_duration_secs: float,
image_size: tuple[int, int],
) -> None:
“””
Runs the colour transition loop.

Args:
color_start_rgb: The beginning colour in RGB format.
color_end_rgb: The ending colour in RGB format.
time_steps: The variety of time steps for the transition.
time_duration_secs: The length of the transition in seconds.
image_size: The scale of the pictures to be generated.
“””

img_shape = (image_size[1], image_size[0], 3)
num_steps = int(fps * time_duration_secs)

for t in np.linspace(0, 1, num_steps):
color_rgb_trans = interpolate_color_rgb(color_start_rgb, color_end_rgb, t)
color_hue_trans = interpolate_color_hsv(color_start_rgb, color_end_rgb, t)

img_rgb = np.full(form=img_shape, fill_value=color_rgb_trans, dtype=np.uint8)
img_hsv = np.full(form=img_shape, fill_value=color_hue_trans, dtype=np.uint8)

composite = cv2.hconcat((img_rgb, img_hsv))
composite_bgr = cv2.cvtColor(composite, cv2.COLOR_RGB2BGR)

cv2.imshow(“Shade Transition”, composite_bgr)

key = cv2.waitKey(1000 // fps) & 0xFF
if key == ord(“q”):
break

cv2.destroyAllWindows()

Now we will merely name this perform with two colours for which we wish to visualize the transition. Under I visualize the transition from blue to yellow.

run_transition_loop(
color_start_rgb=(0, 0, 255), # Blue
color_end_rgb=(255, 255, 0), # Yellow
fps=25,
time_duration_secs=5,
image_size=(512, 256),
)

The distinction is sort of drastic. Whereas the saturation and brightness stay fixed in the correct animation, they alter significantly for the transition that interpolates immediately within the RGB house.

For extra implementation particulars, try the total supply code within the GitHub repository:

https://github.com/trflorian/auto-color-filter

All visualizations on this submit had been created by the writer.

[ad_2]

Source link

Tags: Color SpaceData ScienceHSVmachine learningOpencv PythonPythonRGB
Previous Post

ZachXBT reveals Coinbase users lost another $45M in a week to ongoing social engineering scams

Next Post

Track Your Topps VeeFriends Chrome 2025 Collection with the Base and Manga Speckle Interactive Checklists | by VeeFriends | May, 2025

Next Post
Track Your Topps VeeFriends Chrome 2025 Collection with the Base and Manga Speckle Interactive Checklists | by VeeFriends | May, 2025

Track Your Topps VeeFriends Chrome 2025 Collection with the Base and Manga Speckle Interactive Checklists | by VeeFriends | May, 2025

VeeFriends Chrome 2025: Refractor Scene Swap

VeeFriends Chrome 2025: Refractor Scene Swap

Congressional Roundtable Highlights Urgent Need for Crypto Policy Overhaul

Congressional Roundtable Highlights Urgent Need for Crypto Policy Overhaul

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Social icon element need JNews Essential plugin to be activated.

CATEGORIES

  • Analysis
  • Artificial Intelligence
  • Blockchain
  • Crypto/Coins
  • DeFi
  • Exchanges
  • Metaverse
  • NFT
  • Scam Alert
  • Web3
No Result
View All Result

SITEMAP

  • About us
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Terms and Conditions
  • Cookie Privacy Policy
  • Contact us

Copyright © 2024 Digital Currency Pulse.
Digital Currency Pulse is not responsible for the content of external sites.

No Result
View All Result
  • Home
  • Crypto/Coins
  • NFT
  • AI
  • Blockchain
  • Metaverse
  • Web3
  • Exchanges
  • DeFi
  • Scam Alert
  • Analysis
Crypto Marketcap

Copyright © 2024 Digital Currency Pulse.
Digital Currency Pulse is not responsible for the content of external sites.