您的问题似乎特别是在询问 2 级。但是超过 2 级呢?所以我在下面添加了一个代码,它可以对任何颜色级别进行分色。
import numpy as np
import cv2
im = cv2.imread('messi5.jpg')
n = 2 # Number of levels of quantization
indices = np.arange(0,256) # List of all colors
divider = np.linspace(0,255,n+1)[1] # we get a divider
quantiz = np.int0(np.linspace(0,255,n)) # we get quantization colors
color_levels = np.clip(np.int0(indices/divider),0,n-1) # color levels 0,1,2..
palette = quantiz[color_levels] # Creating the palette
im2 = palette[im] # Applying palette on image
im2 = cv2.convertScaleAbs(im2) # Converting image back to uint8
cv2.imshow('im2',im2)
cv2.waitKey(0)
cv2.destroyAllWindows()
这段代码在 Numpy中使用了一种称为调色板方法的方法,它比遍历像素非常快。您可以在此处找到更多详细信息如何使用它来加速代码:Numpy 中的快速数组操作
以下是我在不同级别获得的结果:
原始图像:

2级:

4级:

8级:

等等...