【问题标题】:How to have a partial grayscale image using Python Pillow (PIL)?如何使用 Python Pillow (PIL) 获得部分灰度图像?
【发布时间】:2021-03-04 18:01:54
【问题描述】:

例子:

  • 第一张图片:原始图片。
  • 第二、第三和第四图像:输出 I 想要。

我知道 PIL 有方法 PIL.ImageOps.grayscale(image) 返回第四张图像,但它没有参数来生成第二张和第三张图像(部分灰度)。

【问题讨论】:

    标签: python python-3.x image image-processing python-imaging-library


    【解决方案1】:
    from PIL import ImageEnhance
    # value: float between 0.0 (grayscale) and 1.0 (original)
    ImageEnhance.Color(image).enhance(value)
    

    P.S.:Mark 的解决方案有效,但似乎增加了曝光率。

    【讨论】:

      【解决方案2】:

      当您将图像转换为灰度时,您实际上是在对其进行去饱和以去除饱和颜色。所以,为了达到你想要的效果,你可能想转换成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')
      

      当然,将整个饱和度通道设置为零以获得全灰度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-05
        • 1970-01-01
        • 2012-03-30
        • 2018-08-15
        • 1970-01-01
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多