使用python改变颜色的色调

时间:2012-06-16 13:19:02

标签: python colors rgb philips-hue

我正在寻找一种方法来改变颜色的色调,知道它的RGB成分,然后用获得的RGB替换旧RGB的所有实例。例如,我想要红色变成紫色,浅红色,浅紫色等...... 它可以通过改变颜色的色调在photoshop中完成。

到目前为止我的想法如下:将RGB转换为HLS,然后更改Hue。

这是迄今为止的代码(多个颜色已更改,而不只是一个,在“列表”列表中定义):

(你可能会注意到,我只是一个初学者而且代码本身很脏;更干净的部分可能来自其他SO用户) 非常感谢!

import colorsys

from tempfile import mkstemp
from shutil import move
from os import remove, close

def replace(file, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file)
    #Move new file
    move(abs_path, file)

def decimal(var):
    return '{:g}'.format(float(var))

list=[[60,60,60],[15,104,150],[143,185,215],[231,231,231],[27,161,253],[43,43,43],[56,56,56],[255,255,255],[45,45,45],[5,8,10],[23,124,193],[47,81,105],[125,125,125],[0,0,0],[24,24,24],[0,109,166],[0,170,255],[127,127,127]]

for i in range(0,len(list)):
    r=list[i][0]/255
    g=list[i][1]/255
    b=list[i][2]/255
    h,l,s=colorsys.rgb_to_hls(r,g,b)
    print(decimal(r*255),decimal(g*255),decimal(b*255))
    h=300/360
    str1=str(decimal(r*255)) + "," + str(decimal(g*255)) + "," + str(decimal(b*255))
    r,g,b=colorsys.hls_to_rgb(h, l, s)
    print(decimal(r*255),decimal(g*255),decimal(b*255))
    str2=str(decimal(r*255)) + "," + str(decimal(g*255)) + "," + str(decimal(b*255))
    replace("Themes.xml",str1,str2)

编辑:问题非常简单:R,G,B和H必须介于0和1之间,我将它们设置在0到255之间以及0和360之间。更新了代码。

1 个答案:

答案 0 :(得分:2)

您的颜色序列使用整数,但colorsys使用介于0.0和1.0之间的浮点值。在将它们通过之前将所有数字除以255.,然后乘以255并在将它们取回后截断。