简体   繁体   English

如何使用 Python Pillow (PIL) 获得部分灰度图像?

[英]How to have a partial grayscale image using Python Pillow (PIL)?

Example:例子:

部分灰度

  • 1st image: the original image.第一张图:原图。
  • 2nd, 3rd and 4th images: the outputs I want.第二、第三和第四张图像:我想要的输出。

I know PIL has the method PIL.ImageOps.grayscale(image) that returns the 4th image, but it doesn't have parameters to produce the 2nd and 3rd ones (partial grayscale).我知道 PIL 有方法PIL.ImageOps.grayscale(image)返回第 4 个图像,但它没有参数来生成第 2 个和第 3 个(部分灰度)。

When you convert an image to greyscale, you are essentially desaturating it to remove saturated colours.当您将图像转换为灰度时,您实际上是在对其进行去饱和处理以去除饱和颜色。 So, in order to achieve your desired effect, you probably want to convert to HSV mode, reduce the saturation and convert back to RGB mode.因此,为了达到您想要的效果,您可能希望转换为HSV模式,降低饱和度并转换回 RGB 模式。

from PIL import Image

# Open input image
im = Image.open('potato.png')

# Convert to HSV mode and separate the channels
H, S, V = im.convert('HSV').split()

# Halve the saturation - you might consider 2/3 and 1/3 saturation
S = S.point(lambda p: p//2)

# Recombine channels
HSV = Image.merge('HSV', (H,S,V))

# Convert to RGB and save
result = HSV.convert('RGB')
result.save('result.png')

在此处输入图片说明


If you prefer to do your image processing in Numpy rather than PIL, you can achieve the same result as above with this code:如果您更喜欢在 Numpy 而不是 PIL 中进行图像处理,您可以使用以下代码获得与上述相同的结果:

from PIL import Image
import numpy as np

# Open input image
im = Image.open('potato.png')

# Convert to HSV and go to Numpy
HSV = np.array(im.convert('HSV'))

# Halve the saturation with Numpy. Hue will be channel 0, Saturation is channel 1, Value is channel 2
HSV[..., 1] = HSV[..., 1] // 2

# Go back to "PIL Image", go back to RGB and save
Image.fromarray(HSV, mode="HSV").convert('RGB').save('result.png')

Of course, set the entire Saturation channel to zero for full greyscale.当然,对于全灰度,将整个饱和度通道设置为零。

from PIL import ImageEnhance
# value: float between 0.0 (grayscale) and 1.0 (original)
ImageEnhance.Color(image).enhance(value)

PS: Mark's solution works, but it seems to be increasing the exposure. PS:Mark 的解决方案有效,但似乎增加了曝光率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM