Написано на скорую руку. Адаптируете при необходимости:
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
from PIL import Image, ImageDraw
import numpy
def get_colors(infile, numcolors=10, swatchsize=20, resize=150):
plt.rcParams['figure.figsize'] = [15, 3]
f,ax = plt.subplots(1,2)
image = Image.open(infile)
orig = image.copy()
image = image.resize((resize, resize))
result = image.convert('P', palette=Image.ADAPTIVE, colors=numcolors)
result.putalpha(0)
colors = result.getcolors(resize*resize)
pal = Image.new('RGB', (swatchsize*numcolors, swatchsize))
draw = ImageDraw.Draw(pal)
posx = 0
for count, col in sorted(colors, key=lambda x: x[0], reverse=True):
draw.rectangle([posx, 0, posx+swatchsize, swatchsize], fill=col)
posx = posx + swatchsize
img = numpy.asarray(pal)
del draw
print('File: ', infile)
for im in sorted(colors, key=lambda x: x[0], reverse=True):
if im[1].index(max(im[1])) == 0:
print(im, 'red')
elif im[1].index(max(im[1])) == 1:
print(im, 'green')
elif im[1].index(max(im[1])) == 2:
print(im, 'blue')
ax[0].imshow(orig)
ax[1].imshow(img)
if __name__ == '__main__':
get_colors('D:\\00\\sample01.jpg', numcolors=1)
get_colors('D:\\00\\sample02.jpg', numcolors=1)
get_colors('D:\\00\\sample03.jpg', numcolors=1)