0

The algorithm I'm using is:

def rgb2hsv(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
    v = mx
    return h, s, v



def my_bgr_to_hsv(bgr_image):
    height, width, c = bgr_image.shape

    hsv_image = np.zeros(shape = bgr_image.shape)

    #The R,G,B values are divided by 255 to change the range from 0..255 to 0..1:

    for h in range(height):
        for w in range(width):
            b,g,r = bgr_image[h,w]
            hsv_image[h,w] = rgb2hsv(r,g,b)      

    return hsv_image

The problem that I'm getting is that when I want to display the image, I get only a black screen.

This is how I'm trying to display the image:

cv.imshow("hello", cv.cvtColor(np.uint8(hsv_image), cv.COLOR_HSV2BGR))

As you can see I convert it back to bgr in order to use cv.imshow, as it only uses bgr.

I don't think I understand enough of opencv or numpy to debug it.

Simply using imshow, shows the original picture in the wrong colors, which makes me think it can't be completely wrong.

  • I'm about to go out, so no time to check, but I believe OpenCV stores Hue values **halved**, i.e. between 0 and 180 (not between 0 and 260) so that they fit into an unsigned byte, so that may be biting you when you convert back. – Mark Setchell May 30 '18 at 19:14
  • Your HSV outputs are floats in 0..359 range. You treat then as an array of `uint8`, that is, of bytes. I suppose that the result of such a treatment would be strange at best. If you want to store such an image on disk, [consider using Pillow](https://stackoverflow.com/a/22237709/223424), or at least find out the image's desired format. – 9000 May 30 '18 at 19:15

1 Answers1

0

Your Hue values are scaled on the range 0 to 359, which is not going to fit into an unsigned 8 bit number, and your Saturations and Values are scaled on the range 0 to 1 which doesn't match your Hues for scale and is going to result in everything rounding to zero (black) when you cinvert it to an unsigned 8 bit number.

I suggest you multiply Saturation and Value by 255 and divide your Hue by 2.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432