平均颜色有点错误。 (np.mean())

时间:2019-09-29 14:42:35

标签: python image numpy rgb

我编写了一个脚本,该脚本在文件中写入图像的平均颜色。但是,它返回一个 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]

2 个答案:

答案 0 :(得分:0)

使用更改行

colors = np.unique(im.reshape(-1, im.shape[2]), axis=0)

colors = im.reshape(-1, im.shape[2])

对于平均颜色计算,颜色是否多次使用很重要,因此使用np.unique会得出错误的结果。

答案 1 :(得分:0)

您可能希望删除unique命令以重现javascript的功能。替换为

colors = im.reshape(-1, im.shape[2])

区别在于您对上颚进行平均(所用的每种颜色都会出现一次),而脚本会对图像进行平均(对图像中出现的颜色进行平均)。