-
Notifications
You must be signed in to change notification settings - Fork 110
/
color_cluster.go
72 lines (56 loc) · 1.44 KB
/
color_cluster.go
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
61
62
63
64
65
66
67
68
69
70
71
72
package rimage
import (
"image"
"github.com/lucasb-eyer/go-colorful"
"github.com/muesli/clusters"
"github.com/muesli/kmeans"
)
func colorFrom(point clusters.Coordinates) Color {
return NewColorFromArray(point)
}
// HSVObservation TODO.
type HSVObservation struct {
c Color
}
// Coordinates TODO.
func (o HSVObservation) Coordinates() clusters.Coordinates {
return o.c.RawFloatArray()
}
// Distance TODO.
func (o HSVObservation) Distance(point clusters.Coordinates) float64 {
return o.c.Distance(colorFrom(point))
}
// ClusterFromImage TODO.
func ClusterFromImage(img *Image, numClusters int) ([]Color, error) {
return ClusterHSV(img.data, numClusters)
}
// ClusterHSV TODO.
func ClusterHSV(data []Color, numClusters int) ([]Color, error) {
all := []clusters.Observation{}
for _, c := range data {
all = append(all, HSVObservation{c})
}
km := kmeans.New()
clusters, err := km.Partition(all, numClusters)
if err != nil {
return nil, err
}
res := []Color{}
for _, c := range clusters {
res = append(res, colorFrom(c.Center))
}
return res, nil
}
// ClusterImage TODO.
func ClusterImage(clusters []Color, img *Image) *image.RGBA {
palette := colorful.FastWarmPalette(len(clusters))
clustered := image.NewRGBA(img.Bounds())
for x := 0; x < img.Width(); x++ {
for y := 0; y < img.Height(); y++ {
p := image.Point{x, y}
idx, _, _ := img.Get(p).Closest(clusters)
clustered.Set(x, y, palette[idx])
}
}
return clustered
}