我正在查看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
答案 0 :(得分:0)
如果您尝试使用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()