forked from fogleman/primitive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
204 lines (180 loc) · 4.91 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/fogleman/primitive/primitive"
"github.com/nfnt/resize"
)
var (
Input string
Outputs flagArray
Background string
Configs shapeConfigArray
Alpha int
InputSize int
OutputSize int
Mode int
Workers int
Nth int
Repeat int
V, VV bool
)
type flagArray []string
func (i *flagArray) String() string {
return strings.Join(*i, ", ")
}
func (i *flagArray) Set(value string) error {
*i = append(*i, value)
return nil
}
type shapeConfig struct {
Count int
Mode int
Alpha int
Repeat int
}
type shapeConfigArray []shapeConfig
func (i *shapeConfigArray) String() string {
return ""
}
func (i *shapeConfigArray) Set(value string) error {
n, _ := strconv.ParseInt(value, 0, 0)
*i = append(*i, shapeConfig{int(n), Mode, Alpha, Repeat})
return nil
}
func init() {
flag.StringVar(&Input, "i", "", "input image path")
flag.Var(&Outputs, "o", "output image path")
flag.Var(&Configs, "n", "number of primitives")
flag.StringVar(&Background, "bg", "", "background color (hex)")
flag.IntVar(&Alpha, "a", 128, "alpha value")
flag.IntVar(&InputSize, "r", 256, "resize large input images to this size")
flag.IntVar(&OutputSize, "s", 1024, "output image size")
flag.IntVar(&Mode, "m", 1, "0=combo 1=triangle 2=rect 3=ellipse 4=circle 5=rotatedrect 6=beziers 7=rotatedellipse 8=polygon")
flag.IntVar(&Workers, "j", 0, "number of parallel workers (default uses all cores)")
flag.IntVar(&Nth, "nth", 1, "save every Nth frame (put \"%d\" in path)")
flag.IntVar(&Repeat, "rep", 0, "add N extra shapes per iteration with reduced search")
flag.BoolVar(&V, "v", false, "verbose")
flag.BoolVar(&VV, "vv", false, "very verbose")
}
func errorMessage(message string) bool {
fmt.Fprintln(os.Stderr, message)
return false
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
// parse and validate arguments
flag.Parse()
ok := true
if Input == "" {
ok = errorMessage("ERROR: input argument required")
}
if len(Outputs) == 0 {
ok = errorMessage("ERROR: output argument required")
}
if len(Configs) == 0 {
ok = errorMessage("ERROR: number argument required")
}
if len(Configs) == 1 {
Configs[0].Mode = Mode
Configs[0].Alpha = Alpha
Configs[0].Repeat = Repeat
}
for _, config := range Configs {
if config.Count < 1 {
ok = errorMessage("ERROR: number argument must be > 0")
}
}
if !ok {
fmt.Println("Usage: primitive [OPTIONS] -i input -o output -n count")
flag.PrintDefaults()
os.Exit(1)
}
// set log level
if V {
primitive.LogLevel = 1
}
if VV {
primitive.LogLevel = 2
}
// seed random number generator
rand.Seed(time.Now().UTC().UnixNano())
// determine worker count
if Workers < 1 {
Workers = runtime.NumCPU()
}
// read input image
primitive.Log(1, "reading %s\n", Input)
input, err := primitive.LoadImage(Input)
check(err)
// scale down input image if needed
size := uint(InputSize)
if size > 0 {
input = resize.Thumbnail(size, size, input, resize.Bilinear)
}
// determine background color
var bg primitive.Color
if Background == "" {
bg = primitive.MakeColor(primitive.AverageImageColor(input))
} else {
bg = primitive.MakeHexColor(Background)
}
// run algorithm
model := primitive.NewModel(input, bg, OutputSize, Workers)
primitive.Log(1, "%d: t=%.3f, score=%.6f\n", 0, 0.0, model.Score)
start := time.Now()
frame := 0
for j, config := range Configs {
primitive.Log(1, "count=%d, mode=%d, alpha=%d, repeat=%d\n",
config.Count, config.Mode, config.Alpha, config.Repeat)
for i := 0; i < config.Count; i++ {
frame++
// find optimal shape and add it to the model
t := time.Now()
n := model.Step(primitive.ShapeType(config.Mode), config.Alpha, config.Repeat)
nps := primitive.NumberString(float64(n) / time.Since(t).Seconds())
elapsed := time.Since(start).Seconds()
primitive.Log(1, "%d: t=%.3f, score=%.6f, n=%d, n/s=%s\n", frame, elapsed, model.Score, n, nps)
// write output image(s)
for _, output := range Outputs {
ext := strings.ToLower(filepath.Ext(output))
percent := strings.Contains(output, "%")
saveFrames := percent && ext != ".gif"
saveFrames = saveFrames && frame%Nth == 0
last := j == len(Configs)-1 && i == config.Count-1
if saveFrames || last {
path := output
if percent {
path = fmt.Sprintf(output, frame)
}
primitive.Log(1, "writing %s\n", path)
switch ext {
default:
check(fmt.Errorf("unrecognized file extension: %s", ext))
case ".png":
check(primitive.SavePNG(path, model.Context.Image()))
case ".jpg", ".jpeg":
check(primitive.SaveJPG(path, model.Context.Image(), 95))
case ".svg":
check(primitive.SaveFile(path, model.SVG()))
case ".gif":
frames := model.Frames(0.001)
check(primitive.SaveGIFImageMagick(path, frames, 50, 250))
}
}
}
}
}
}