我有这个代码可以将颜色减少到最少量的颜色,以帮助识别它是什么;它工作得更早,但现在说它
ValueError: x must consist of vectors of length 3 but has shape (480, 640, 4)
就像我说的那样早些时候工作,但后来我尝试添加'白色',因为白色变成黄色,现在它根本不起作用
import numpy as np
from matplotlib import colors
from scipy.spatial import cKDTree as KDTree
from scipy.misc import face
from PIL import Image
REDUCED_COLOR_SPACE = True
# borrow a list of named colors from matplotlib
if REDUCED_COLOR_SPACE:
use_colors = {k: colors.cnames[k] for k in ['red', 'green', 'blue', 'black', 'yellow', 'purple']}
else:
use_colors = colors.cnames
# translate hexstring to RGB tuple
named_colors = {k: tuple(map(int, (v[1:3], v[3:5], v[5:7]), 3*(16,)))
for k, v in use_colors.items()}
ncol = len(named_colors)
if REDUCED_COLOR_SPACE:
ncol -= 1
no_match = named_colors.pop('purple')
else:
no_match = named_colors['purple']
# make an array containing the RGB values
color_tuples = list(named_colors.values())
color_tuples.append(no_match)
color_tuples = np.array(color_tuples)
color_names = list(named_colors)
color_names.append('no match')
# get example picture
img = Image.open('apple.png')
# build tree
tree = KDTree(color_tuples[:-1])
# tolerance for color match `inf` means use best match no matter how
# bad it may be
tolerance = np.inf
# find closest color in tree for each pixel in picture
dist, idx = tree.query(img, distance_upper_bound=tolerance)
# count and reattach names
counts = dict(zip(color_names, np.bincount(idx.ravel(), None, ncol+1)))
print(counts)
import pylab
pylab.imshow(img)
pylab.savefig('apple.png')
pylab.clf()
pylab.imshow(color_tuples[idx])
pylab.savefig('minimal.png' if REDUCED_COLOR_SPACE else 'reduced.png')
之前确实有效:
它确实起作用了:
问题是:
当我运行它时,我收到此错误
'第45行,在dist中,idx = tree.query(img,distance_upper_bound = tolerance)
在scipy.spatial.ckdtree.cKDTree.query文件“ckdtree.pyx”,第754行 ValueError:x必须由长度为3的向量组成,但具有形状(480,640,4)'
我希望它能拍出我选择的照片,然后像上面发布的示例一样进行更改。
我怎么能意识到这一点?
答案 0 :(得分:0)
你得到的错误是不言自明的。这意味着您的图片处于RGBA
模式,即其中包含Alpha通道,因此其形状为(640, 480, 4)
,通道为R,G,B, A 。
话虽这么说,您需要先将图片转换为RGB
:
img = img.convert("RGB")
然后,我尝试了this问题,我发现解决问题的唯一方法是将您的颜色转换为uint8
格式:
更改此行:
color_tuples = np.array(color_tuples)
使用:
color_tuples = np.array(color_tuples).astype('uint8')
希望它有所帮助!