【问题标题】:Convert an image to grayscale using a limited amount of shades?使用有限数量的阴影将图像转换为灰度?
【发布时间】:2021-02-24 03:17:51
【问题描述】:

我希望将图像转换为灰度,但希望将阴影数量限制为 4-5。这样做的原因是因为我正在尝试创建图像的分层“剪纸”效果,以便我可以将它用作我正在处理的一些艺术品的基础,其中我有 5 种黑白色调可供使用.

如果您对如何使用 Python 实现这一点有更好的想法,我会全力以赴。如果 Python 中已经存在这样的过滤器,那将非常方便,但我似乎找不到任何东西。欣赏它。

项目最终结果如下所示:Image

【问题讨论】:

标签: python python-3.x image filter grayscale


【解决方案1】:

您可以使用 PIL 对此进行量化:

进入这个:

像这样:

from PIL import Image

# Load Paddington and make greyscale
im = Image.open('paddington.png').convert('L')

# Quantize down to 5 shades and save
qu = im.quantize(5)
qu.save('result.png')

您可以像这样使用 ImageMagick 检查颜色:

magick identify -verbose result.png

样本输出

Image:
  Filename: result.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: PseudoClass
  Geometry: 400x400+0+0
  Units: Undefined
  Colorspace: sRGB
  Type: Grayscale
  Base type: Undefined
  Endianness: Undefined
  Depth: 8-bit
  Channel depth:
    Red: 8-bit
    Green: 8-bit
    Blue: 8-bit
  Channel statistics:
    Pixels: 160000
    Red:
      min: 20  (0.0784314)
      max: 207 (0.811765)
      mean: 89.5854 (0.351315)
      median: 109 (0.427451)
      standard deviation: 63.0322 (0.247185)
      kurtosis: -1.0005
      skewness: 0.501687
      entropy: 0.974919
    Green:
      min: 20  (0.0784314)
      max: 207 (0.811765)
  ...
  ...
  ... 
  Colors: 5                             <--- HERE
  Histogram:
    44023: (20,20,20) #141414 grey8
    38190: (53,53,53) #353535 srgb(53,53,53)
    33061: (109,109,109) #6D6D6D srgb(109,109,109)
    26051: (152,152,152) #989898 srgb(152,152,152)
    18675: (207,207,207) #CFCFCF grey81
  ...
  ...

关键词:Python、图像处理、量化、减色。

【讨论】:

    【解决方案2】:

    这里是如何在 Python/OpenCV 中直接量化到 5 个灰度级。

    输入:

    import cv2
    import numpy as np
    
    # arguments
    num_colors = 5
    
    # read input
    img = cv2.imread("bear2.png")
    
    # convert to gray as float in range 0 to 1
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = gray.astype(np.float32)/255
    
    # quantize and convert back to range 0 to 255 as 8-bits
    result = 255*np.floor(gray*num_colors+0.5)/num_colors
    result = result.clip(0,255).astype(np.uint8)
    
    # save result
    cv2.imwrite('bear2_gray5.png', result)
    
    cv2.imshow('result', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    【讨论】:

    • 那是 6 种颜色?
    • 谢谢,马克。所以从 num_colors 中减去 1。
    猜你喜欢
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2010-11-20
    • 2021-06-06
    相关资源
    最近更新 更多