Implementation:Kornia Kornia Hsv Conversion
| Knowledge Sources | |
|---|---|
| Domains | Vision, Color_Processing |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
This module provides differentiable conversion between RGB and HSV (Hue, Saturation, Value) color spaces.
Description
hsv.py is a module in the Kornia library's color subpackage implementing bidirectional RGB-to-HSV color space conversion. The rgb_to_hsv function computes Hue (in radians, range [0, 2*pi]), Saturation (range [0, 1]), and Value (range [0, 1]) from an RGB image. The conversion handles edge cases with an epsilon parameter for numerical stability. The hsv_to_rgb function converts HSV back to RGB using a sectored lookup approach. Both functions support arbitrary batch dimensions and produce differentiable outputs. Each function has a corresponding nn.Module wrapper (RgbToHsv and HsvToRgb).
Usage
Import this module when you need to separate or manipulate hue, saturation, and brightness independently, for example in color augmentation, color filtering, or artistic style transfer.
Code Reference
Source Location
- Repository: Kornia
- File: kornia/color/hsv.py
- Lines: 1-174
Signature
def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: ...
def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor: ...
class RgbToHsv(nn.Module):
def __init__(self, eps: float = 1e-6) -> None: ...
def forward(self, image: torch.Tensor) -> torch.Tensor: ...
class HsvToRgb(nn.Module):
def forward(self, image: torch.Tensor) -> torch.Tensor: ...
Import
from kornia.color import rgb_to_hsv, hsv_to_rgb
from kornia.color import RgbToHsv, HsvToRgb
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| image (rgb_to_hsv) | torch.Tensor | Yes | RGB image with shape (*, 3, H, W). Values in range (0, 1). |
| eps (rgb_to_hsv) | float | No | Epsilon for numerical stability. Default: 1e-8. |
| image (hsv_to_rgb) | torch.Tensor | Yes | HSV image with shape (*, 3, H, W). H in [0, 2*pi], S in [0, 1], V in [0, 1]. |
Outputs
| Name | Type | Description |
|---|---|---|
| rgb_to_hsv return | torch.Tensor | HSV image with shape (*, 3, H, W). Channel order: H (hue in radians [0, 2*pi]), S (saturation [0, 1]), V (value [0, 1]). |
| hsv_to_rgb return | torch.Tensor | RGB image with shape (*, 3, H, W). |
Usage Examples
Basic Usage
import torch
from kornia.color import rgb_to_hsv, hsv_to_rgb
# Convert RGB to HSV
rgb = torch.rand(1, 3, 128, 128)
hsv = rgb_to_hsv(rgb)
print(hsv.shape) # torch.Size([1, 3, 128, 128])
# Modify saturation (channel index 1)
hsv[:, 1, :, :] = hsv[:, 1, :, :] * 0.5 # reduce saturation by 50%
# Convert back to RGB
rgb_desaturated = hsv_to_rgb(hsv)
print(rgb_desaturated.shape) # torch.Size([1, 3, 128, 128])
# Using nn.Module wrappers in a pipeline
from kornia.color import RgbToHsv, HsvToRgb
to_hsv = RgbToHsv(eps=1e-6)
to_rgb = HsvToRgb()
hsv_out = to_hsv(rgb)
rgb_out = to_rgb(hsv_out)