繁体   English   中英

OpenCV kmeans 错误:(-215) python

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

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

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)

我已阅读有关 C++ 中相同错误的其他帖子,但我无法使其正常工作。 请帮忙!

编辑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()

您可以单独运行此代码以检查出了什么问题。 将图像大小调整为小于 90x90 会导致它崩溃。 任何大于 91x91 的东西都可以工作。 谁能解释为什么以及如何解决它?

使用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