File: kmeans.py

package info (click to toggle)
opencv 2.4.9.1%2Bdfsg-1%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 126,800 kB
  • ctags: 62,729
  • sloc: xml: 509,055; cpp: 490,794; lisp: 23,208; python: 21,174; java: 19,317; ansic: 1,038; sh: 128; makefile: 72
file content (60 lines) | stat: -rwxr-xr-x 1,859 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python
import urllib2
import cv2.cv as cv
from random import randint
MAX_CLUSTERS = 5

if __name__ == "__main__":

    color_tab = [
        cv.CV_RGB(255, 0,0),
        cv.CV_RGB(0, 255, 0),
        cv.CV_RGB(100, 100, 255),
        cv.CV_RGB(255, 0,255),
        cv.CV_RGB(255, 255, 0)]
    img = cv.CreateImage((500, 500), 8, 3)
    rng = cv.RNG(-1)

    cv.NamedWindow("clusters", 1)

    while True:
        cluster_count = randint(2, MAX_CLUSTERS)
        sample_count = randint(1, 1000)
        points = cv.CreateMat(sample_count, 1, cv.CV_32FC2)
        clusters = cv.CreateMat(sample_count, 1, cv.CV_32SC1)

        # generate random sample from multigaussian distribution
        for k in range(cluster_count):
            center = (cv.RandInt(rng)%img.width, cv.RandInt(rng)%img.height)
            first = k*sample_count/cluster_count
            last = sample_count
            if k != cluster_count:
                last = (k+1)*sample_count/cluster_count

            point_chunk = cv.GetRows(points, first, last)

            cv.RandArr(rng, point_chunk, cv.CV_RAND_NORMAL,
                       cv.Scalar(center[0], center[1], 0, 0),
                       cv.Scalar(img.width*0.1, img.height*0.1, 0, 0))


        # shuffle samples
        cv.RandShuffle(points, rng)

        cv.KMeans2(points, cluster_count, clusters,
                   (cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 10, 1.0))

        cv.Zero(img)

        for i in range(sample_count):
            cluster_idx = int(clusters[i, 0])
            pt = (cv.Round(points[i, 0][0]), cv.Round(points[i, 0][1]))
            cv.Circle(img, pt, 2, color_tab[cluster_idx], cv.CV_FILLED, cv.CV_AA, 0)

        cv.ShowImage("clusters", img)

        key = cv.WaitKey(0) % 0x100
        if key in [27, ord('q'), ord('Q')]:
            break

    cv.DestroyWindow("clusters")