-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcandidate.go
276 lines (222 loc) · 6.2 KB
/
candidate.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package polygen
import (
"encoding/gob"
"image"
"image/color"
"log"
"math/rand"
"github.com/llgcode/draw2d/draw2dimg"
)
const (
MutationAlpha = iota
MutationColor = iota
MutationPoint = iota
MutationZOrder = iota
MutationAddOrDeletePoint = iota
)
const (
PopulationCount = 10
MaxPolygonPoints = 6
MinPolygonPoints = 3
PointMutationMaxDistance = 5
MutationsPerIteration = 1 // originally had 3, but 1 seems to work best here
)
var (
Mutations = []int{MutationColor, MutationPoint, MutationAlpha, MutationZOrder, MutationAddOrDeletePoint}
)
func init() {
// need to give an example of a concrete type for the color.Color interface
gob.Register(randomColor())
}
// Candidate is a potential solution (set of polygons) to the problem of how to best represent the reference image.
type Candidate struct {
W, H int
Polygons []*Polygon
img *image.RGBA // candidate this image for evaluation
Fitness uint64
}
// Polygon is a set of points with a given fill color.
type Polygon struct {
Points []Point
color.Color
}
// Point defines a vertex in a Polygon.
type Point struct {
X, Y int
}
func (p *Polygon) copyOf() *Polygon {
result := &Polygon{Color: p.Color}
for i := 0; i < len(p.Points); i++ {
result.Points = append(result.Points, p.Points[i])
}
return result
}
func randomCandidate(w, h, polyCount int) *Candidate {
result := &Candidate{W: w, H: h}
for i := 0; i < polyCount; i++ {
result.Polygons = append(result.Polygons, randomPolygon(w, h))
}
return result
}
func randomPolygon(maxW, maxH int) *Polygon {
result := &Polygon{}
result.Color = randomColor()
numPoints := RandomInt(MinPolygonPoints, MaxPolygonPoints+1)
for i := 0; i < numPoints; i++ {
result.addPoint(randomPoint(maxW, maxH))
}
return result
}
func randomPoint(maxW, maxH int) Point {
return Point{rand.Intn(maxW), rand.Intn(maxH)}
}
// Copies the Candidate, minus the img (we assume the copy will be mutated/rendered after).
func (c *Candidate) copyOf() *Candidate {
result := &Candidate{W: c.W, H: c.H}
for i := 0; i < len(c.Polygons); i++ {
result.Polygons = append(result.Polygons, c.Polygons[i].copyOf())
}
return result
}
// mutateInPlace chooses a random polygon from the candidate and makes a random mutation to it.
func (c *Candidate) mutateInPlace() {
locus := rand.Intn(len(c.Polygons))
poly := c.Polygons[locus]
switch randomMutation() {
case MutationColor:
poly.Color = mutateColor(poly.Color)
case MutationAlpha:
poly.Color = mutateAlpha(poly.Color)
case MutationPoint:
pointIndex := rand.Intn(len(poly.Points))
poly.Points[pointIndex].mutateNearby(c.W, c.H)
case MutationZOrder:
shufflePolygonZOrder(c.Polygons)
case MutationAddOrDeletePoint:
if len(poly.Points) == MinPolygonPoints {
// can't delete
poly.addPoint(randomPoint(c.W, c.H))
} else if len(poly.Points) == MaxPolygonPoints {
// can't add
poly.deleteRandomPoint()
} else {
// we can do either add or delete
if RandomBool() {
poly.addPoint(randomPoint(c.W, c.H))
} else {
poly.deleteRandomPoint()
}
}
default:
log.Fatal("fell through")
}
}
func (p *Polygon) addPoint(point Point) {
p.Points = append(p.Points, point)
}
func (p *Polygon) deleteRandomPoint() {
i := rand.Intn(len(p.Points))
p.Points = append(p.Points[:i], p.Points[i+1:]...)
}
// mutateNearby alters the point by moving it a few pixels.
func (p *Point) mutateNearby(maxW, maxH int) {
xDelta := rand.Intn(PointMutationMaxDistance + 1)
if RandomBool() {
xDelta = -xDelta
}
x := p.X + xDelta
if x < 0 {
x = 0
}
if x >= maxW {
x = maxW - 1
}
p.X = x
yDelta := rand.Intn(PointMutationMaxDistance + 1)
if RandomBool() {
yDelta = -yDelta
}
y := p.Y + yDelta
if y < 0 {
y = 0
}
if y >= maxH {
y = maxH - 1
}
p.Y = y
}
// randomColor returns a color with completely random values for RGBA.
func randomColor() color.Color {
// start with non-premultiplied RGBA
c := color.NRGBA{R: uint8(rand.Intn(256)), G: uint8(rand.Intn(256)), B: uint8(rand.Intn(256)), A: uint8(rand.Intn(256))}
return color.RGBAModel.Convert(c)
}
// mutateColor returns a new color with a single random mutation to one of the RGBA values.
func mutateColor(c color.Color) color.Color {
// get the non-premultiplied rgba values
nrgba := color.NRGBAModel.Convert(c).(color.NRGBA)
// randomly select one of the r/g/b/a values to mutate
i := rand.Intn(4)
val := uint8(rand.Intn(256))
switch i {
case 0:
nrgba.R = val
case 1:
nrgba.G = val
case 2:
nrgba.B = val
case 3:
nrgba.A = val
}
return color.RGBAModel.Convert(nrgba)
}
// mutateAlpha a new color whose alpha level has been randomly modified.
func mutateAlpha(c color.Color) color.Color {
// get the non-premultiplied rgba values
nrgba := color.NRGBAModel.Convert(c).(color.NRGBA)
nrgba.A = uint8(rand.Intn(256))
return color.RGBAModel.Convert(nrgba)
}
func randomMutation() int {
return Mutations[rand.Intn(len(Mutations))]
}
func (cd *Candidate) renderImage() {
cd.img = image.NewRGBA(image.Rect(0, 0, cd.W, cd.H))
gc := draw2dimg.NewGraphicContext(cd.img)
// paint the whole thing black to start
gc.SetFillColor(color.Black)
gc.MoveTo(0, 0)
gc.LineTo(float64(cd.W-1), 0)
gc.LineTo(float64(cd.W-1), float64(cd.H-1))
gc.LineTo(0, float64(cd.H-1))
gc.Close()
gc.Fill()
gc.SetLineWidth(1)
for _, polygon := range cd.Polygons {
gc.SetStrokeColor(polygon.Color)
gc.SetFillColor(polygon.Color)
firstPoint := polygon.Points[0]
gc.MoveTo(float64(firstPoint.X), float64(firstPoint.Y))
for _, point := range polygon.Points[1:] {
gc.LineTo(float64(point.X), float64(point.Y))
}
gc.Close()
//gc.FillStroke()
gc.Fill()
}
}
func (cd *Candidate) drawAndSave(destFile string) error {
log.Printf("saving output image to: %s", destFile)
return draw2dimg.SaveToPngFile(destFile, cd.img)
}
func shufflePolygonZOrder(polygons []*Polygon) {
for i := range polygons {
j := rand.Intn(i + 1)
polygons[i], polygons[j] = polygons[j], polygons[i]
}
}
// sorting
type ByFitness []*Candidate
func (cds ByFitness) Len() int { return len(cds) }
func (cds ByFitness) Swap(i, j int) { cds[i], cds[j] = cds[j], cds[i] }
func (cds ByFitness) Less(i, j int) bool { return cds[i].Fitness < cds[j].Fitness }