Color spaces

In the following image BGR = (z, h, v) blue is zero green increases in the horizontal direction, red increases in the horizhontal direction. We have black, red, green and yellow in the 4 corners.

../_images/rgb2.png
# Compose an RGB color with 3 trackbars
import cv2 as cv
import numpy as np

v = np.fromfunction(lambda i, j: i, (256, 256), dtype=np.uint8)
h = np.fromfunction(lambda i, j: j, (256, 256), dtype=np.uint8)
z = np.zeros((256, 256), dtype=np.uint8)

img = cv.merge([z, h, v])
cv.imshow('window', img)

cv.waitKey(0)
cv.destroyAllWindows()

rgb2.py

Sliding through the color cube

The RGB colors space is a cube of dimension $256 x 256 x 256$. In the following program we display Blue and Green and use the trackbar to select the Red component.

color/rgb3.png
# Trackbar to go through 1 axis
import cv2 as cv
import numpy as np

def trackbar(x):
    img[:, :, 2] = x
    cv.imshow('window', img)

img = np.zeros((256, 256, 3), dtype=np.uint8)

for i in range(256):
    img[i, :, 0] = i
    img[:, i, 1] = i

cv.imshow('window', img)
cv.createTrackbar('red', 'window', 0, 255, trackbar)

cv.waitKey(0)
cv.destroyAllWindows()

rgb3.py

The HSV colorspace

The HSV color space is a cube of dimension 180x256x256.

../_images/hsv2.png
# Trackbar to go through 1 axis
import cv2 as cv
import numpy as np

def trackbar(x):
    img[:, :, 2] = x
    rgb = cv.cvtColor(img, cv.COLOR_HSV2BGR)
    cv.imshow('window', rgb)

img = np.zeros((180, 256, 3), dtype=np.uint8)

for i in range(180):
    img[i, :, 0] = i

for i in range(256):
    img[:, i, 1] = i

cv.imshow('window', img)
cv.createTrackbar('saturation', 'window', 0, 255, trackbar)

cv.waitKey(0)
cv.destroyAllWindows()

hsv2.py

Extracting an object based on hue

../_images/hsv3.png
# Extract an object in HSV color space based on hue
import cv2 as cv
import numpy as np

img = cv.imread('legos.jpg')
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)

def trackbar(x):
    lower = (x, 30, 30)
    upper = (x+5, 250, 250)
    mask = cv.inRange(hsv, lower, upper)
    img2 = cv.bitwise_and(img, img, mask=mask)
    cv.imshow('window', np.vstack([img, img2]))

cv.imshow('window', img)
cv.createTrackbar('hue', 'window', 0, 179, trackbar)

cv.waitKey(0)
cv.destroyAllWindows()

hsv3.py