RGB to HSV via PIL and colorsys

笑着哭i 提交于 2019-12-01 08:33:48

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')

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

def rgb2hsv(image):
    return image.convert('HSV')

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!