Cara menggunakan python rgb to hsv

To convert RGB color values to HSV color values in Python, import colorsys library, call rgb_to_hsv() function, and pass the Red, Green, and Blue values as arguments.

rgb_to_hsv() function takes Red, Blue, and Green values as arguments, and returns a tuple containing Hue, Saturation, and Value.

The Red, Blue, and Green values must be normalised to the range [0, 1] prior to conversion for input to rgb_to_hsv() function.

Examples

In the following program, we take an RGB value and convert it to HSV value.

Python Program

import colorsys

(r, g, b) = (0.2, 0.4, 0.4)
(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
print('HSV : ', h, s, v)
Run

Output

HSV :  0.5 0.5 0.4

Convert RGB to HSV with values in 8-bit Ranges

In the following program, we are getting RGB values in the range specified in the below table, and we shall convert it to HSV with the ranges mentioned in the below table.

ComponentRangeR (Red)[0, 255]G (Green)[0, 255]B (Blue)[0, 255]H (Hue)[0, 179]S (Saturation)[0, 255]V (Value)[0, 255]

Python Program

import colorsys

#input
(r, g, b) = (142, 244, 85)
#normalize
(r, g, b) = (r / 255, g / 255, b / 255)
#convert to hsv
(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
#expand HSV range
(h, s, v) = (int(h * 179), int(s * 255), int(v * 255))
print('HSV : ', h, s, v)
Run

Output

HSV :  48 166 244

Summary

In this Python Tutorial, we learned how to convert an RBG color value to HSV color value, using colorsys library.

Note: RGB - RGB (Red, Green, Blue) describes what kind of light needs to be emitted to produce a given color. Light is added together to create form from darkness. RGB stores individual values for red, green and blue. RGB is not a color space, it is a color model. There are many different RGB color spaces derived from this color model, some of which appear below.

HSV - (hue, saturation, value), also known as HSB (hue, saturation, brightness), is often used by artists because it is often more natural to think about a color in terms of hue and saturation than in terms of additive or subtractive color components. HSV is a transformation of an RGB colorspace, and its components and colorimetry are relative to the RGB colorspace from which it was derived.

Sample Solution:-

Python Code:

def rgb_to_hsv(r, g, b):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = (df/mx)*100
    v = mx*100
    return h, s, v

print(rgb_to_hsv(255, 255, 255))
print(rgb_to_hsv(0, 215, 0))

Sample Output:

(0, 0.0, 100.0)                                                                                               
(120.0, 100.0, 84.31372549019608)

Flowchart:

Cara menggunakan python rgb to hsv

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to implement Euclidean Algorithm to compute the greatest common divisor (gcd).
Next: Write a Python program to find perfect squares between two given numbers.

What is the difficulty level of this exercise?

Easy Medium Hard

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Annotated Assignment Statement:

This might not seem as impressive as some other tricks but it's a new syntax that was introduced to Python in recent years and just good to be aware of.

Annotated assignments allow the coder to leave type hints in the code. These don't have any enforcing power at least not yet. It's still nice to be able to imply some type hints and definitely offers more options than only being able to comment regarding expected types of variables.

RGB, HSV dan CMYK adalah contoh color space, sederhananya color space adalah cara untuk mempresentasikan warna. CMYK umum digunakan untuk industri printing, sementara RGB dan HSV untuk media digital.

RGB

RGB adalah model color dengan cara menggabungkan warna Red, Green dan Blue. Perlu diperhatikan, OpenCV menyimpan warna dalam urutan BGR.

HSV

Adalah Hue, Saturation dan Value, dimana:

  • Hue: menunjukan warna itu sendiri. Range (0 – 179).
  • Saturation: Intensitas warna. Makin tinggi saturasi, makin rendah warna putih. Range (0 -255).
  • Value: Kecerahan. Makin tinggi value, makin cerah, makin rendah makin gelap. Range (0 -255).

NOTE: HSV memudahkan segmentasi warna. Mode RGB, sulit untuk melakukan filtering warna tertentu.

Cara menggunakan python rgb to hsv

Cara menggunakan python rgb to hsv

Dari color wheel diatas, dapat dipetakan

  • Red : 165 – 15
  • Green: 45 – 75
  • Blue: 90-120

Cara mengakses channel RGB

Untuk mengakses channel RGB, gunakan index ketiga dari array image.

r = img_rgb [ :, :, 0]
g = img_rgb [ :, :, 1]
b = img_rgb [ :, :, 2]
import numpy as np
import matplotlib.pyplot as plt
import cv2

img = cv2.imread('chureito-pagoda.jpg')

%matplotlib inline

img_copy = np.copy(img)
img_rgb = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)

r = img_rgb [ :, :, 0]
g = img_rgb [ :, :, 1]
b = img_rgb [ :, :, 2]

f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10))
ax1.set_title('Red')
ax1.imshow(r, cmap='gray')
ax2.set_title('Green')
ax2.imshow(g, cmap='gray')
ax3.set_title('Blue')
ax3.imshow(b, cmap='gray')

Cara Mengakses Channel HSV

Sama seperti RGB, untuk mengakses channel HSV, gunakan index ketiga dari array image.

h = hsv [ :, :, 0]
s = hsv [ :, :, 1]
v = hsv [ :, :, 2]
hsv = cv2.cvtColor(img_copy, cv2.COLOR_RGB2HSV)
h = hsv [ :, :, 0]
s = hsv [ :, :, 1]
v = hsv [ :, :, 2]

f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10))
ax1.set_title('Hue')
ax1.imshow(h, cmap='gray')
ax2.set_title('Saturation')
ax2.imshow(s, cmap='gray')
ax3.set_title('Value')
ax3.imshow(v, cmap='gray')

Image yang digunakan pada tutorial ini https://drive.google.com/file/d/1sPBiKDTOomEwOqdN1CN8aUKKuVSsb737/view?usp=sharing

Anda juga bisa mengakses file google colab di https://colab.research.google.com/drive/1XzTtQ8_2dPHiF3dJv5olgSJYR9Fc6xo0?usp=sharing