user10548418
user10548418

Reputation:

OpenCV RGB2HSV color space convertion gives wrong results, colors aren't similar

Why the color space conversion goes wrong (images are not roughly similar) when I use OpenCV COLOR_RGB2HSV and goes right when using image.convert('HSV') ? What I'm doing wrong?

import cv2
from PIL import Image

image = Image.open('picture_1.jpg')

img1=cv2.imread('picture_1.jpg')
img2=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)
img3=cv2.cvtColor(img2,cv2.COLOR_RGB2HSV)
img4=cv2.cvtColor(img3,cv2.COLOR_HSV2RGB)

fig, ax = plt.subplots(2, 2, figsize=(16, 6), subplot_kw=dict(xticks=[], yticks=[]))
fig.subplots_adjust(wspace=0.05)
ax[0][0].imshow(img1)
ax[0][0].set_title('BGR', size=16)
ax[0][1].imshow(img2)
ax[0][1].set_title('RGB', size=16);
ax[1][0].imshow(img3)
ax[1][0].set_title('HSV', size=16);
ax[1][1].imshow(image.convert('HSV'))
ax[1][1].set_title('HSV', size=16);

I got this results:

enter image description here

Upvotes: 1

Views: 2825

Answers (2)

Shashiwadana
Shashiwadana

Reputation: 517

OpenCV assumes images are in BGR format in both imwrite and imshow methods. So it handles the HSV matrix as BGR when saving or showing an image. Another thing is in OpenCV documentation they say that, "For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]. Different softwares use different scales. So if you are comparing OpenCV values with them, you need to normalize these ranges." You can find it here

Upvotes: 2

Mark Setchell
Mark Setchell

Reputation: 208043

HSV is scaled differently from how you might expect in OpenCV. When your data is np.uint8 it can only be in the range 0..255, so Hue values are divided by 2 and instead of 0..360 as you might expect, they range from 0..180.

By the way, mixing up a load of matplotlib in your question already about PIL/Pillow and OpenCV reduces the likelihood of getting an answer - best to keep it simple.

Upvotes: 1

Related Questions