forked from esimov/pigo
/
main.go
270 lines (229 loc) · 6.32 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
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
package main
import (
"encoding/json"
"flag"
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"io/ioutil"
"log"
"math"
"os"
"path/filepath"
"time"
"github.com/esimov/pigo/core"
"github.com/fogleman/gg"
)
const banner = `
┌─┐┬┌─┐┌─┐
├─┘││ ┬│ │
┴ ┴└─┘└─┘
Go (Golang) Face detection library.
Version: %s
`
// Version indicates the current build version.
var Version string
var (
// Flags
source = flag.String("in", "", "Source image")
destination = flag.String("out", "", "Destination image")
cascadeFile = flag.String("cf", "", "Cascade binary file")
minSize = flag.Int("min", 20, "Minimum size of face")
maxSize = flag.Int("max", 1000, "Maximum size of face")
shiftFactor = flag.Float64("shift", 0.1, "Shift detection window by percentage")
scaleFactor = flag.Float64("scale", 1.1, "Scale detection window by percentage")
angle = flag.Float64("angle", 0.0, "0.0 is 0 radians and 1.0 is 2*pi radians")
iouThreshold = flag.Float64("iou", 0.2, "Intersection over union (IoU) threshold")
circleMarker = flag.Bool("circle", false, "Use circle as detection marker")
outputAsJSON = flag.Bool("json", false, "Output face box coordinates into a json file")
)
var dc *gg.Context
// faceDetector struct contains Pigo face detector general settings.
type faceDetector struct {
cascadeFile string
minSize int
maxSize int
shiftFactor float64
scaleFactor float64
iouThreshold float64
}
// detectionResult contains the coordinates of the detected faces and the base64 converted image.
type detectionResult struct {
rects []image.Rectangle
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, fmt.Sprintf(banner, Version))
flag.PrintDefaults()
}
flag.Parse()
if len(*source) == 0 || len(*destination) == 0 || len(*cascadeFile) == 0 {
log.Fatal("Usage: pigo -in input.jpg -out out.png -cf data/facefinder")
}
fileTypes := []string{".jpg", ".jpeg", ".png"}
ext := filepath.Ext(*destination)
if !inSlice(ext, fileTypes) {
log.Fatalf("Output file type not supported: %v", ext)
}
if *scaleFactor < 1 {
log.Fatal("Scale factor must be greater than 1.")
}
// Progress indicator
s := new(spinner)
s.start("Processing...")
start := time.Now()
fd := newFaceDetector(*cascadeFile, *minSize, *maxSize, *shiftFactor, *scaleFactor, *iouThreshold)
faces, err := fd.detectFaces(*source)
if err != nil {
log.Fatalf("Detection error: %v", err)
}
_, rects, err := fd.drawFaces(faces, *circleMarker)
if err != nil {
log.Fatalf("Error creating the image output: %s", err)
}
resp := detectionResult{
rects: rects,
}
out, err := json.Marshal(resp)
if *outputAsJSON {
ioutil.WriteFile("output.json", out, 0644)
}
s.stop()
fmt.Printf("\nDone in: \x1b[92m%.2fs\n", time.Since(start).Seconds())
}
// newFaceDetector initialises the constructor function.
func newFaceDetector(cf string, minSize, maxSize int, shf, scf, iou float64) *faceDetector {
return &faceDetector{
cascadeFile: cf,
minSize: minSize,
maxSize: maxSize,
shiftFactor: shf,
scaleFactor: scf,
iouThreshold: iou,
}
}
// detectFaces run the detection algorithm over the provided source image.
func (fd *faceDetector) detectFaces(source string) ([]pigo.Detection, error) {
src, err := pigo.GetImage(source)
if err != nil {
return nil, err
}
pixels := pigo.RgbToGrayscale(src)
cols, rows := src.Bounds().Max.X, src.Bounds().Max.Y
dc = gg.NewContext(cols, rows)
dc.DrawImage(src, 0, 0)
cParams := pigo.CascadeParams{
MinSize: fd.minSize,
MaxSize: fd.maxSize,
ShiftFactor: fd.shiftFactor,
ScaleFactor: fd.scaleFactor,
ImageParams: pigo.ImageParams{
Pixels: pixels,
Rows: rows,
Cols: cols,
Dim: cols,
},
}
cascadeFile, err := ioutil.ReadFile(fd.cascadeFile)
if err != nil {
return nil, err
}
pigo := pigo.NewPigo()
// Unpack the binary file. This will return the number of cascade trees,
// the tree depth, the threshold and the prediction from tree's leaf nodes.
classifier, err := pigo.Unpack(cascadeFile)
if err != nil {
return nil, err
}
// Run the classifier over the obtained leaf nodes and return the detection results.
// The result contains quadruplets representing the row, column, scale and detection score.
faces := classifier.RunCascade(cParams, *angle)
// Calculate the intersection over union (IoU) of two clusters.
faces = classifier.ClusterDetections(faces, fd.iouThreshold)
return faces, nil
}
// drawFaces marks the detected faces with a circle in case isCircle is true, otherwise marks with a rectangle.
func (fd *faceDetector) drawFaces(faces []pigo.Detection, isCircle bool) ([]byte, []image.Rectangle, error) {
var (
qThresh float32 = 5.0
rects []image.Rectangle
)
for _, face := range faces {
if face.Q > qThresh {
if isCircle {
dc.DrawArc(
float64(face.Col),
float64(face.Row),
float64(face.Scale/2),
0,
2*math.Pi,
)
} else {
dc.DrawRectangle(
float64(face.Col-face.Scale/2),
float64(face.Row-face.Scale/2),
float64(face.Scale),
float64(face.Scale),
)
}
rects = append(rects, image.Rect(
face.Col-face.Scale/2,
face.Row-face.Scale/2,
face.Scale,
face.Scale,
))
dc.SetLineWidth(2.0)
dc.SetStrokeStyle(gg.NewSolidPattern(color.RGBA{R: 255, G: 0, B: 0, A: 255}))
dc.Stroke()
}
}
img := dc.Image()
output, err := os.OpenFile(*destination, os.O_CREATE|os.O_RDWR, 0755)
if err != nil {
return nil, nil, err
}
ext := filepath.Ext(output.Name())
switch ext {
case ".jpg", ".jpeg":
jpeg.Encode(output, img, &jpeg.Options{Quality: 100})
case ".png":
png.Encode(output, img)
}
rf, err := ioutil.ReadFile(*destination)
return rf, rects, err
}
type spinner struct {
stopChan chan struct{}
}
// Start process
func (s *spinner) start(message string) {
s.stopChan = make(chan struct{}, 1)
go func() {
for {
for _, r := range `-\|/` {
select {
case <-s.stopChan:
return
default:
fmt.Printf("\r%s%s %c%s", message, "\x1b[92m", r, "\x1b[39m")
time.Sleep(time.Millisecond * 100)
}
}
}
}()
}
// End process
func (s *spinner) stop() {
s.stopChan <- struct{}{}
}
// inSlice check if a slice contains the string value.
func inSlice(ext string, types []string) bool {
for _, t := range types {
if t == ext {
return true
}
}
return false
}