如何使用cv2.kmeans中的标签作为列表的索引?

2024-10-08 23:18:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查看here中的代码。我无法让它运行,也无法与开发者取得联系。我做了一些修改以使其正常工作,但我不明白为什么会出现错误:

TypeError: only integer scalar arrays can be converted to a scalar index

我已经打印了这个类型,我注意到它的类型是<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])

错误:

^{pr2}$

Tags: toinforlennprangearraycv2
1条回答
网友
1楼 · 发布于 2024-10-08 23:18:38

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

import numpy as np

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

TypeError: only integer scalar arrays can be converted to a scalar index

只要看一下^{}的一个例子,就可以清楚地看出,您应该将您的ravel展平,labels,即:

^{pr2}$

相关问题 更多 >

    热门问题