我编写了一个脚本,该脚本在文件中写入图像的平均颜色。但是,它返回bit错误的值。
# 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()
示例:(image)-在Photoshop和here中,平均颜色为[105、99、89],但我的脚本返回[107,100,90]
更改行与
colors = np.unique(im.reshape(-1, im.shape[2]), axis=0)
到
colors = im.reshape(-1, im.shape[2])
对于平均颜色计算,是否多次使用一种颜色很重要,因此使用np.unique
将给出错误的结果。
您可能希望删除unique
命令来重现javascript的操作。替换为
colors = im.reshape(-1, im.shape[2])
不同之处在于,您对上颚进行平均(所用的每种颜色都会出现一次),而脚本会对图像进行平均(对图像中出现的颜色进行平均)。