![](/img/trans.png)
[英]How to send embedded image created using PIL/pillow as email (Python 3)
[英]How to have a partial grayscale image using Python Pillow (PIL)?
當您將圖像轉換為灰度時,您實際上是在對其進行去飽和處理以去除飽和顏色。 因此,為了達到您想要的效果,您可能希望轉換為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')
當然,對於全灰度,將整個飽和度通道設置為零。
from PIL import ImageEnhance
# value: float between 0.0 (grayscale) and 1.0 (original)
ImageEnhance.Color(image).enhance(value)
PS:Mark 的解決方案有效,但似乎增加了曝光率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.