I wrote a script, that writes average color of image in a file. But, it returns a bit wrong values.
# coding=utf-8
from __future__ import print_function
import cv2, sys, os
import numpy as np
palette = []
if len(sys.argv) < 2:
print(u'Drag file on me.')
print(u'(Press Enter to close)',end='')
raw_input()
sys.exit()
if not os.path.exists(sys.argv[1]):
print(u'Invalid file name.')
print(u'(Press Enter to close)',end='')
raw_input()
sys.exit()
for file in sys.argv[1:]:
im = cv2.imread(file)
if im is None:
print(u'The specified file is corrupted or is not a picture.')
print(u'(Press Enter to close)',end='')
raw_input()
sys.exit()
colors = np.unique(im.reshape(-1, im.shape[2]), axis=0)
color = np.flip(colors.mean(axis=0,dtype=np.float64).astype(int)).tolist()
palette.append([color,os.path.basename(file)[:-4]])
palette = np.array(palette)
palette = palette[palette[:,0].argsort(kind='mergesort')]
out = open('palette.txt','w')
out.write(str(palette.tolist()))
out.close()
Example: (image) – in Photoshop, and here, average color is [105, 99, 89], but my script returns [107,100,90]
2
Answers
Change the line with
colors = np.unique(im.reshape(-1, im.shape[2]), axis=0)
to
colors = im.reshape(-1, im.shape[2])
For an average color calculation, it matters if a color is used more than once, so using
np.unique
will give an incorrect result.You may want to remove the
unique
command to reproduce what the javascript is doing. Replace it withThe difference is that you average the palate (every color used appears once), while the script averages the image (averages colors as they appear in the image).