-
Notifications
You must be signed in to change notification settings - Fork 23
/
mask.go
80 lines (71 loc) · 1.69 KB
/
mask.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
73
74
75
76
77
78
79
80
package wordclouds
import (
"image/color"
"math"
"github.com/fogleman/gg"
)
// Mask creates a slice of box structs from a given mask image to be passed to wordclouds.MaskBoxes.
func Mask(path string, width int, height int, exclude color.RGBA) []*Box {
res := make([]*Box, 0)
img, err := gg.LoadPNG(path)
if err != nil {
panic(err)
}
// scale
imgw := img.Bounds().Dx()
imgh := img.Bounds().Dy()
wr := float64(width) / float64(imgw)
wh := float64(height) / float64(imgh)
scalingRatio := math.Min(wr, wh)
// center
xoffset := 0.0
yoffset := 0.0
if scalingRatio*float64(imgw) < float64(width) {
xoffset = (float64(width) - scalingRatio*float64(imgw)) / 2
res = append(res, &Box{
float64(height),
0.0,
xoffset,
0,
})
res = append(res, &Box{
float64(height),
float64(width) - xoffset,
float64(width),
0,
})
}
if scalingRatio*float64(imgh) < float64(height) {
yoffset = (float64(height) - scalingRatio*float64(imgh)) / 2
res = append(res, &Box{
yoffset,
0.0,
float64(width),
0,
})
res = append(res, &Box{
float64(height),
0.0,
float64(width),
float64(height) - yoffset,
})
}
step := 3
bounds := img.Bounds()
for i := bounds.Min.X; i < bounds.Max.X; i = i + step {
for j := bounds.Min.Y; j < bounds.Max.Y; j = j + step {
r, g, b, a := img.At(i, j).RGBA()
er, eg, eb, ea := exclude.RGBA()
if r == er && g == eg && b == eb && a == ea {
b := &Box{
math.Min(float64(j+step)*scalingRatio+yoffset, float64(height)),
float64(i)*scalingRatio + xoffset,
math.Min(float64(i+step)*scalingRatio+xoffset, float64(width)),
float64(j)*scalingRatio + yoffset,
}
res = append(res, b)
}
}
}
return res
}