【问题标题】:ValueError: x must consist of vectors of length 3 but has shape (480, 640, 4)ValueError: x 必须由长度为 3 的向量组成,但具有形状 (480, 640, 4)
【发布时间】:2018-05-27 11:32:38
【问题描述】:

我有这段代码可以将颜色减少到最少的颜色,以帮助识别它是什么;它之前工作过,但现在它说

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')

之前确实有效:

之后它确实起作用了:

问题是:
当我运行它时,我得到了这个错误

'line 45, in dist, idx = tree.query(img, distance_upper_bound=tolerance)
文件“ckdtree.pyx”,第 754 行,在 scipy.spatial.ckdtree.cKDTree.query
ValueError: x 必须由长度为 3 的向量组成,但形状为 (480, 640, 4)'

我希望它可以拍摄我选择的照片并像我上面发布的示例一样进行更改。

我怎样才能意识到这一点?

【问题讨论】:

  • 您能否更具体地说明您正在尝试什么问题以及您期望的结果是什么?
  • @Neb 知道为什么吗?

标签: python python-3.x matplotlib


【解决方案1】:

您得到的错误是不言自明的。这意味着您的图像处于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')

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多