使用有限数量的阴影将图像转换为灰度?

Convert an image to grayscale using a limited amount of shades?

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

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

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

你可以使用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,图像处理,量化,减色。

下面是如何在 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()