简体   繁体   English

OpenCV kmeans 错误:(-215) python

[英]OpenCV kmeans error: (-215) python

Error: error: (-215) (unsigned)labels[i] < (unsigned)K in function kmeans错误:错误:(-215) (unsigned)labels[i] < (unsigned)K in function kmeans

self.cluster[i] represents some calculated pixel position. self.cluster[i]表示一些计算出的像素位置。

img = numpy.asarray(img)
Z = img.reshape((-1,3))
Z = numpy.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
#prepare centers
labels = numpy.zeros(k)
for i in range(k):
    labels[i] = self.cluster[i].j * img.shape[0] + self.cluster[i].i
print(Z)
ret, label, center = cv2.kmeans(Z, k, None, criteria, 10, cv2.KMEANS_USE_INITIAL_LABELS, labels)

I have read the other posts about the same error in c++, but I could not get it to work.我已阅读有关 C++ 中相同错误的其他帖子,但我无法使其正常工作。 Please help!请帮忙!

EDIT1:编辑1:

import numpy as np
import sys
sys.path.append('/usr/local/lib/python3.5/site-packages')
import cv2

img = cv2.imread('image.jpg')
img = cv2.resize(img, (90,90))
Z = img.reshape((-1,3))

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 4

labels = np.zeros(K)
labels[0] = 1
labels[1] = 100
labels[2] = 500
labels[3] = 1000
print(labels)
print(Z.shape)
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_USE_INITIAL_LABELS, labels)

# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))

cv2.imshow('res2',res2)
cv2.waitKey(0)
cv2.destroyAllWindows()

You can run this code alone to check what's wrong.您可以单独运行此代码以检查出了什么问题。 By resizing the image to less than 90x90 causes it to crash.将图像大小调整为小于 90x90 会导致它崩溃。 Anything bigger than 91x91 works.任何大于 91x91 的东西都可以工作。 Can anyone explain why and maybe how to fix it?谁能解释为什么以及如何解决它?

使用cv2.KMEANS_PP_CENTERScv2.KMEANS_RANDOM_CENTERS而不是cv2.KMEANS_USE_INITIAL_LABELS时,我的问题解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM