【问题标题】:How can I use the labels from cv2.kmeans as index for a list?如何使用 cv2.kmeans 中的标签作为列表的索引?
【发布时间】:2017-08-10 12:29:57
【问题描述】:

我正在查看来自here 的代码。而且我无法让它运行,也无法与开发人员取得联系。我已经进行了一些修改以使其正常工作,但我无法弄清楚为什么会出现错误:

TypeError: 只有整数标量数组可以转换为标量索引

我已经打印了类型,我注意到它的类型是<class 'list'>。我试图查找各种资源,但无法理解导致问题的原因。

# applying kmeans on colwise white pixel counts
z = np.float32(a)
# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 12, 0.0)
# Set flags (Just to avoid line break in the code)
flags = cv2.KMEANS_RANDOM_CENTERS
K = 5
# Apply KMeans
compactness,labels,centers = cv2.kmeans(z,K,None,criteria,10,flags)

# define colors to be used
blue = np.array([255,0,0])
green = np.array([0,255,0])
red = np.array([0,0,255])
tur = np.array([255,255,0])
purple = np.array([255,0,255])
yellow = np.array([0,255,255])

colors = [red,green,blue,purple,tur]
imcpy = np.empty_like(img)
np.copyto(imcpy,img)

# draw colors according to cluster labels
for i in range(len(a)):
        row,col = a[i][0],a[i][1]
        thisColor = colors[labels[i]]
        imcpy[row][col] = thisColor

for c in range(len(centers)):
        Crow,Ccol = centers[c][0],int(centers[c][1])
        for row in range(height):
                imcpy[row][Ccol] = np.array([255,255,255])

# characters
charHeight, charWidth = height,45
char_imgs = []
centers = sorted(centers,key=lambda x: x[1])
for c in range(len(centers)):
        Crow,Ccol = centers[c][0],int(centers[c][1])
        x1 = (Ccol-int(charWidth/2)) if ((Ccol-int(charWidth/2)) > 0) else 0
        x2 = (Ccol+int(charWidth/2)) if ((Ccol+int(charWidth/2)) < width) else width
        char_imgs.append(charcpy[0:height , x1:x2])

for x in range(len(char_imgs)):
        opPath = outDIR+"/"+ chars[x]
        if not os.path.exists(opPath):
                os.makedirs(opPath)
        cv2.imwrite(opPath +"/" + str(x) +"_" + file, char_imgs[x])

错误:

/prep# python3 prepdata.py ../images/train_120.png 
Traceback (most recent call last): File "prepdata.py", line 95, in <module> thisColor = colors[labels[i]] 
TypeError: only integer scalar arrays can be converted to a scalar index

【问题讨论】:

  • 请打印完整的错误信息。

标签: python python-3.x opencv numpy


【解决方案1】:

如果您尝试使用 NumPy 数组(即使它只是整数)索引 Python 列表(您的 colors),则会发生此异常:

import numpy as np

color = ['red', 'blue', 'yellow']
labels = np.array([[1, 2], [2, 3]])
color[labels[1]]

TypeError: 只有整数标量数组可以转换为标量索引

只要看一下cv2.kmeans 的例子,就可以清楚地知道你应该扁平化(ravel)你的labels,即:

labels = labels.ravel()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 2012-08-06
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多