python - 如何使用 Python Pillow (PIL) 获得部分灰度图像?
问题描述
例子:
- 第一张图片:原始图片。
- 第二、第三和第四张图像:我想要的输出。
我知道 PIL 有PIL.ImageOps.grayscale(image)
返回第四张图像的方法,但它没有生成第二张和第三张图像的参数(部分灰度)。
解决方案
当您将图像转换为灰度时,您实际上是在对其进行去饱和以去除饱和颜色。因此,为了达到您想要的效果,您可能需要转换为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')
如果您更喜欢在 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')
当然,将整个饱和度通道设置为零以获得全灰度。
推荐阅读
- c - 为什么子进程管道显示在具有不同管道详细信息的父进程中
- react-native - 从 saga 中的 socket.io 事件中发送动作
- android - 应为 BEGIN_OBJECT,但在第 1 行第 1 列应用程序崩溃时为 STRING
- laravel - 背景图像在 foreach 循环中不起作用
- r - Removing tick marks, tick=FALSE do not seem to work
- javascript - Magento - 前端和后端没有 js 文件
- c# - 如何在 .net 核心中添加 ws-security 标头?
- angular - Angular - 如何使用自定义输入组件子组件测试容器组件?
- llvm - Enable a llvm pass for Os but not O2
- java - 我如何在java中发送带有“soap”的文件