4

I have written a function which converts an Image from RGB > HSV. However, when I save the new image the only thing I get is a black image. What should I fix to get it solved?

Any help is kindly appreciated!

My code:

def HSVColor(img):
    if isinstance(img,Image):
        r,g,b = img.split()
        Hdat = []
        Sdat = []
        Vdat = [] 
        for rd,gn,bl in zip(r.getdata(),g.getdata(),b.getdata()) :
            h,s,v = colorsys.rgb_to_hsv(rd/255.,gn/255.,bl/255.)
            Hdat.append(int(h*255.))
            Sdat.append(int(l*255.))
            Vdat.append(int(s*255.))
        r.putdata(Hdat)
        g.putdata(Sdat)
        b.putdata(Vdat)
        return Image.merge('RGB',(r,g,b))
    else:
        return None
bolzano
  • 816
  • 2
  • 13
  • 30

3 Answers3

27

Just FYI, with a recent copy of Pillow, one should probably use

def rgb2hsv(image):
    return image.convert('HSV')
K3---rnc
  • 6,717
  • 3
  • 31
  • 46
  • True though Image.save() may choke on the result. You'll need to trick Pillow into seeing the channels as RGB by copying them into an RGB Image object – bjorke Jan 21 '16 at 17:31
  • According to the docs this is not supported: https://pillow.readthedocs.io/en/4.1.x/reference/Image.html#PIL.Image.Image.convert – whlteXbread Apr 09 '17 at 04:11
  • @whlteXbread The docs just say all possible conversions between RGB, CYMK and L modes are supported. For other conversions, support is limited, e.g. RGB → HSV works whereas L → HSV might not. – K3---rnc Dec 06 '18 at 17:13
4

i think you are trying to do the impossible, although you can transform rgb to hsv colour (and vice versa) values, according to wikipedia jpg images can only be stored in rgb or cmyk models.

Tony Cronin
  • 1,623
  • 1
  • 24
  • 30
  • I'mm guessing the goal is to get a kind of false color image, not to get a native hsv image. – Mark Ransom Mar 06 '14 at 23:02
  • @markransom, you can convert colours, but the color model of jpg is rgb. perhaps png or gif might be a better way to go for this use case? – Tony Cronin Mar 06 '14 at 23:12
2

Didn't you mix the module Image and its class Image?

The following code works for me (change the isinstance(img,Image.Image) part):

import Image, colorsys    

def HSVColor(img):
    if isinstance(img,Image.Image):
        r,g,b = img.split()
        Hdat = []
        Sdat = []
        Vdat = [] 
        for rd,gn,bl in zip(r.getdata(),g.getdata(),b.getdata()) :
            h,s,v = colorsys.rgb_to_hsv(rd/255.,gn/255.,bl/255.)
            Hdat.append(int(h*255.))
            Sdat.append(int(s*255.))
            Vdat.append(int(v*255.))
        r.putdata(Hdat)
        g.putdata(Sdat)
        b.putdata(Vdat)
        return Image.merge('RGB',(r,g,b))
    else:
        return None

a = Image.open('/tmp/a.jpg')
b = HSVColor(a)
b.save('/tmp/b.jpg')
fredtantini
  • 15,966
  • 8
  • 49
  • 55