5
5
"image/color"
6
6
"math"
7
7
"math/rand"
8
+ "sync"
8
9
)
9
10
10
11
type cluster struct {
@@ -37,14 +38,23 @@ func getClusters(k int, set image.Image) []*cluster {
37
38
}
38
39
39
40
func partition (clr []* cluster , set image.Image ) {
41
+ var w sync.WaitGroup
42
+ w .Add (set .Bounds ().Max .Y * set .Bounds ().Max .X )
43
+ var mtx sync.Mutex
44
+
40
45
// assign all data points to the nearest cluster
41
46
for y := set .Bounds ().Min .Y ; y < set .Bounds ().Max .Y ; y ++ {
42
47
for x := set .Bounds ().Min .X ; x < set .Bounds ().Max .X ; x ++ {
43
- v := set .At (x , y )
44
- i := indexNewCentroid (clr , v )
45
- clr [i ].members = append (clr [i ].members , image .Pt (x , y ))
48
+ go func (x , y int ) {
49
+ i := indexNewCentroid (clr , set .At (x , y ))
50
+ mtx .Lock ()
51
+ clr [i ].members = append (clr [i ].members , image .Pt (x , y )) // with go
52
+ mtx .Unlock ()
53
+ w .Done ()
54
+ }(x , y )
46
55
}
47
56
}
57
+ w .Wait ()
48
58
49
59
var getAverage = func (pts []image.Point ) color.Color {
50
60
lPts := len (pts )
@@ -63,7 +73,7 @@ func partition(clr []*cluster, set image.Image) {
63
73
i := uint8 (rSum / uint32 (lPts ))
64
74
j := uint8 (gSum / uint32 (lPts ))
65
75
k := uint8 (bSum / uint32 (lPts ))
66
- return color.RGBA {R : i , G : j , B : k , A : 0 }
76
+ return color.RGBA {R : i , G : j , B : k , A : 100 }
67
77
}
68
78
69
79
// update each centroid per cluster
@@ -94,9 +104,8 @@ func indexNewCentroid(clr []*cluster, p color.Color) (idx int) {
94
104
min := uint32 (math .MaxUint32 )
95
105
96
106
for i , c := range clr {
97
- cl := c .centroid
98
107
// find cluster with lowest color-distance
99
- d := euclidDis (cl , p )
108
+ d := euclidDis (c . centroid , p )
100
109
if d < min {
101
110
min = d
102
111
idx = i
0 commit comments