Python 3,改变图像的颜色 [英] Python 3, changing colour of an image

查看:630
本文介绍了Python 3,改变图像的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用RGB值更改整个图像的颜色的最简单方法是什么?我尝试过 wand ,但文档对我没有什么意义,我只能找到改变 Pillow 文档中颜色的强度。 p>

我在网上尝试过多个解决方案,但是他们没有做我想要的,或者已经过时,不能工作。



我想要它,以便整个图像被着色,我可以通过改变RGB颜色控制色调,位像这样:



http://cdn.makeuseof.com/ wp-content / uploads / 2012/11 / Folder-Colorizer-Color-Manager.jpg?69fac7



我可以自行实现轮子,改变颜色部分让我困惑。希望这将是一个容易的解决方案:)

解决方案

这是一个Python 3版本的代码在我的其他答案。除了为了使用 枕头而必须更改的导入内容,它几乎完全相同 PIL (因为只支持Python 3)。我做的其他更改是将 print 语句更改为函数调用,其中 map()函数用于创建 luts 查找表变量。

  $ b from PIL.ImageColor import getcolor,getrgb 
from PIL.ImageOps import grayscale

def image_tint(src,tint ='#ffffff'):
if Image.isStringType src):#file path?
src = Image.open(src)
如果src.mode不在['RGB','RGBA']:
raise TypeError('不支持的源图像模式:{} (src.mode))
src.load()

tr,tg,tb = getrgb(tint)
tl = getcolor(tint,L)#tint color总体亮度
如果不是tl:tl = 1#避免除以零
tl = float(tl)#计算亮度保持色调因子
sr,sg,sb = map(lambda tv:tv / tl,(tr,tg,tb))#每个组件
#调整
#创建查找表以将亮度映射到调整的色调
#(使用浮点数学计算table)
luts =(tuple(map(lambda lr:int(lr * sr + 0.5),range(256)))+
tuple(map(lambda lg:int(lg * sg + 0.5 ),
1 = grayscale(src)#8-bit luminosity(src)),
bb(bbb:int(lb * sb + 0.5),range(256)版本的整个图像
如果Image.getmodebands(src.mode)< 4:
merge_args =(src.mode,(l,l,l))#用于灰度的RGB版本
else:#包含src图像的alpha层副本
a = Image.new L,src.size)
a.putdata(src.getdata(3))
merge_args =(src.mode,(l,l,l,a))#用于RGBA灰度级
luts + = tuple(range(256))#用于复制的alpha值的1:1映射

return Image.merge(* merge_args).point(luts)

if __name__ =='__main__':
import os
import sys

input_image_path ='Dn3CeZB.png'
print('tinting{} '.format(input_image_path))

root,ext = os.path.splitext(input_image_path)
suffix ='_result_py {}'。format(sys.version_info [0])
result_image_path = root + suffix + ext

print('creating'{}'format(result_image_path))
result = image_tint(input_image_path,'#383D2D')
如果os.path.exists(result_image_path):#删除任何以前的结果文件
os.remove(result_image_path)
result.save(result_image_path)#文件名的扩展名确定格式

print('done')

这里是前后的图片。 测试图片和色彩颜色与您在使用时所说的相同,当您遇到问题。结果看起来非常相似的Py2版本,对你,对我...我错过了什么?




what is the easiest way to change the colour of the whole image with a RGB value? I have tried wand, however the documentation didn't make much sense to me, and I can only find changing the intensity of the colours in the Pillow documentation.

I tried multiple solutions online, however either they didn't do what I wanted, or were out of date and didn't work.

I want it so that the whole image gets tinted and I can control the tint by changing the RGB colour, bit like this:

http://cdn.makeuseof.com/wp-content/uploads/2012/11/Folder-Colorizer-Color-Manager.jpg?69fac7

I can implement the wheel myself, however the actual changing colour part is confusing me. Hopefully it will be an easy solution :)

解决方案

Here's a Python 3 version of the code in my other answer. It's almost identical except for the imports which had to be changed in order to use the pillow fork of the PIL (because only it supports Python 3). The other changes I made were changing print statements into function calls and where the map() function is used to create the luts look-up table variable.

from PIL import Image
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale

def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component
                                                      # adjustments
    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr*sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg*sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb*sb + 0.5), range(256))))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)

if __name__ == '__main__':
    import os
    import sys

    input_image_path = 'Dn3CeZB.png'
    print('tinting "{}"'.format(input_image_path))

    root, ext = os.path.splitext(input_image_path)
    suffix = '_result_py{}'.format(sys.version_info[0])
    result_image_path = root+suffix+ext

    print('creating "{}"'.format(result_image_path))
    result = image_tint(input_image_path, '#383D2D')
    if os.path.exists(result_image_path):  # delete any previous result file
        os.remove(result_image_path)
    result.save(result_image_path)  # file name's extension determines format

    print('done')

Here's before and after images. The test image and tint color are the same as what you said you were using when you encountered the problem. The results look very similar to the Py2 version, to yours, and OK to me...am I missing something?

这篇关于Python 3,改变图像的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆