Python openCV: kmeans示例不工作

6 投票
1 回答
4794 浏览
提问于 2025-04-18 02:21

我正在学习openCV的例子,但有时候这些例子无法运行。在很多情况下,我只需要做一些小改动,它们就能正常工作。不过在这个例子中,我到现在还没找到解决办法。如果我运行下面的代码,在kmeans那一行就会出错。我检查了数据类型,似乎一切都没问题。有没有人知道哪里出了问题?谢谢!

代码示例来自 https://github.com/Itseez/opencv:

'''
Keyboard shortcuts:
    ESC   - exit
    space - generate new distribution
'''

import numpy as np
import cv2
from gaussian_mix import make_gaussians

if __name__ == '__main__':
    cluster_n = 5
    img_size = 512

    print __doc__

    # generating bright palette
    colors = np.zeros((1, cluster_n, 3), np.uint8)
    colors[0,:] = 255
    colors[0,:,0] = np.arange(0, 180, 180.0/cluster_n)
    colors = cv2.cvtColor(colors, cv2.COLOR_HSV2BGR)[0]

    while True:
        print 'sampling distributions...'
        points, _ = make_gaussians(cluster_n, img_size)

        term_crit = (cv2.TERM_CRITERIA_EPS, 30, 0.1)

        ret, labels, centers = cv2.kmeans(points, cluster_n, None, term_crit, 10, 0)

        img = np.zeros((img_size, img_size, 3), np.uint8)
        for (x, y), label in zip(np.int32(points), labels.ravel()):
            c = map(int, colors[label])
            cv2.circle(img, (x, y), 1, c, -1)

        cv2.imshow('gaussian mixture', img)
        ch = 0xFF & cv2.waitKey(0)
        if ch == 27:
            break
    cv2.destroyAllWindows()

错误信息:

TypeError: an integer is required

1 个回答

12

我在使用3.x版本的openCV示例代码,但我实际上是在运行2.4.8版本。因为这两个版本的写法不一样,所以会有些不同。

ret, labels, centers = cv2.kmeans(points, cluster_n, term_crit, 10, 0)

撰写回答