且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PIL模块中更改图像颜色

更新时间:2023-01-28 18:41:02

许多颜色操作***在 HSV ,您可以通过以下方式在PIL中获得它:

Many colour operations are best done in a colourspace such as HSV which you can get in PIL with:

HSV = rgb.convert('HSV')

然后您可以使用split()获取3个单独的频道:

You can then use split() to get 3 separate channels:

H, S, V = hsv.split()

现在,您可以更改颜色.您似乎对自己想要的东西有点毛躁.如果要更改颜色的强度,即使它们的饱和度降低而鲜艳度降低,请降低S(饱和度).如果您想将红色更改为紫色,即更改色相,则在色相通道中添加一些内容.如果要使图像更亮或更暗,请更改值(V)"通道.

Now you can change your colours. You seem a little woolly on what you want. If you want to change the intensity of the colours, i.e. make them less saturated and less vivid decrease the S (Saturation). If you want to change the reds to purples, i.e. change the Hues, then add something to the Hue channel. If you want to make the image brighter or darker, change the Value (V) channel.

完成后,将merge((H,S,V))编辑过的通道合并在一起,并使用convert('RGB')转换回RGB.

When you have finished, merge merge((H,S,V)) the edited channels back together and convert back to RGB with convert('RGB').

请参见拆分和合并和处理单个频段. "rel ="nofollow noreferrer">此页面.

See Splitting and Merging and Processing Individual Bands on this page.

以下是使用此图片的示例:

Here is an example, using this image:

这是加载图像,转换为HSV色彩空间,拆分通道,进行一些处理,重新组合通道并还原为RGB色彩空间并保存结果的基本框架.

Here is the basic framework to load the image, convert to HSV colourspace, split the channels, do some processing, recombine the channels and revert to RGB colourspace and save the result.

#!/usr/bin/env python3

from PIL import Image

# Load image and create HSV version
im = Image.open('colorwheel.jpg')
HSV= im.convert('HSV')

# Split into separate channels
H, S, V = HSV.split()

######################################
########## PROCESSING HERE ###########
######################################

# Recombine processed H, S and V back into a recombined image
HSVr = Image.merge('HSV', (H,S,V))
# Convert recombined HSV back to reconstituted RGB
RGBr = HSVr.convert('RGB')

# Save processed result
RGBr.save('result.png')

因此,如果您找到标有此处进行处理" 的块,并在其中放置将饱和度除以2的代码,它将使颜色的鲜艳度降低:

So, if you find the chunk labelled "PROCESSING HERE" and put code in there to divide the saturation by 2, it will make the colours less vivid:

# Desaturate the colours by halving the saturation
S = S.point(lambda p: p//2) 

如果相反,我们将亮度(V)减半,如下所示:

If, instead, we halve the brightness (V), like this:

# Halve the brightness
V=V.point(lambda p: p//2) 

结果将更暗:

如果相反,我们向色相添加80,则所有颜色将围绕圆旋转-这称为色相旋转" :

If, instead, we add 80 to the Hue, all the colours will rotate around the circle - this is called a "Hue rotation":

# Rotate Hues around the Hue circle by 80 on a range of 0..255, so around 1/3 or a circle, i.e. 120 degrees:
H = H.point(lambda p: p+80) 

这给出了这一点: