Skip to content Skip to sidebar Skip to footer

Python Cv2 Color Space Conversion Fidelity Loss

Observe the following image: Observe the following Python code: import cv2 img = cv2.imread('rainbow.png', cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # convert i

Solution 1:

Back at a computer now - try like this:

#!/usr/bin/env python3
import numpy as np
import cv2

img = cv2.imread("rainbow.png", cv2.IMREAD_COLOR)
img = img.astype(np.float32)/255           # go to 32-bit float on 0..1

img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # convert it to hsv
img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR) # convert back to BGR
cv2.imwrite("output.png", (img*255).astype(np.uint8))

I think the problem is that when you use unsigned 8-bit representation, the Hue gets "squished" from a range of 0..360 into a range of 0..180, in 2 degree increments in order to stay within 8-bit unsigned range of 0..255 causing steps between nearby values. A solution is to move to 32-bit floats and scale to the range 0..1.

Post a Comment for "Python Cv2 Color Space Conversion Fidelity Loss"