-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
220 lines (163 loc) · 4.86 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
// Heavily based on the gocv face detector example
package main
// #cgo LDFLAGS: -framework CoreFoundation -framework IOKit
// void onSystemIdle();
// void onDisplaySleep();
// void onDisplayWakeup();
// #include "sleepwatcher.h"
import "C"
import (
"flag"
"image"
"image/color"
"log"
"os/exec"
"time"
"gocv.io/x/gocv"
)
type detectedFace struct {
confidence float32
top int
bottom int
left int
right int
}
var net gocv.Net
var ratio float64
var mean gocv.Scalar
var swapRGB bool
var window *gocv.Window = nil
var img gocv.Mat
var displaySleeping int
var faceCoveragePercentPtr *float64
var faceDetectionTreshold *float64
var idleTimePtr *int
var debug *bool
func main() {
idleTimePtr = flag.Int("idleCheck", 10, "Idle time in seconds before visual check")
faceCoveragePercentPtr = flag.Float64("minFaceAreaPercent", 5, "Minumum screen area (in %) that needs to be covered by face")
faceDetectionTreshold = flag.Float64("faceDetectionTreshold", 25, "Treshold probability for face detection (in %)")
debug = flag.Bool("debug", false, "Show window with face detection information")
flag.Parse()
*faceCoveragePercentPtr = *faceCoveragePercentPtr / 100
*faceDetectionTreshold = *faceDetectionTreshold / 100
model := "res10_300x300_ssd_iter_140000.caffemodel"
config := "deploy.prototxt"
// open DNN object tracking model
net = gocv.ReadNet(model, config)
if net.Empty() {
log.Printf("Error reading neural network model from : %v %v\n", model, config)
net.Close()
return
}
net.SetPreferableBackend(gocv.NetBackendType(gocv.NetBackendDefault))
net.SetPreferableTarget(gocv.NetTargetType(gocv.NetTargetCPU))
ratio = 1.0
mean = gocv.NewScalar(104, 177, 123, 0)
swapRGB = false
// prepare image matrix
img = gocv.NewMat()
C.setupSleepWatcher(C.int(10 * *idleTimePtr))
}
//export onDisplaySleep
func onDisplaySleep() {
displaySleeping = 1
}
//export onDisplayWakeup
func onDisplayWakeup() {
displaySleeping = 0
}
//export onSystemIdle
func onSystemIdle() {
log.Println("I'm idle!!!!!!")
if displaySleeping == 1 {
log.Println("But display is sleeping...")
return
}
// parse args
deviceID := 0
if *debug && window == nil {
window = gocv.NewWindow("DNN Detection")
}
log.Printf("Start reading device: %v\n", deviceID)
if ok := readImage(deviceID, &img); !ok {
log.Println("Cannot read from device - too dark? Sleeping display anyway")
sleepDisplay()
return
}
// detect faces
numDetectedFaces := 0
// convert image Mat to 300x300 blob that the object detector can analyze
blob := gocv.BlobFromImage(img, ratio, image.Pt(300, 300), mean, swapRGB, false)
// feed the blob into the detector
net.SetInput(blob, "")
// run a forward pass thru the network
prob := net.Forward("")
faces := detectFaces(&img, prob)
prob.Close()
blob.Close()
imgArea := float32(img.Size()[0] * img.Size()[1])
for ind, face := range faces {
faceArea := float32((face.bottom-face.top)*(face.right-face.left)) / imgArea
if ind < 5 {
log.Printf("Confidence %.3f top %d bottom %d left %d right %d area %.3f \n", face.confidence, face.top, face.bottom, face.left, face.right, faceArea)
}
if face.confidence > float32(*faceDetectionTreshold) && faceArea >= float32(*faceCoveragePercentPtr) {
numDetectedFaces++
if *debug {
gocv.Rectangle(&img, image.Rect(face.left, face.top, face.right, face.bottom), color.RGBA{0, 255, 0, 0}, 2)
}
}
}
if *debug {
window.IMShow(img)
if window.WaitKey(1) >= 0 {
return
}
}
if numDetectedFaces == 0 {
log.Println("No face detected in front of computer - sleeping display")
sleepDisplay()
}
}
func sleepDisplay() {
cmd := exec.Command("pmset", "displaysleepnow")
err := cmd.Run()
if err != nil {
log.Printf("Error executing command: %d \n", err)
}
}
func readImage(deviceID int, img *gocv.Mat) bool {
for i := 0; i < 10; i++ {
// open webcam
webcam, err := gocv.OpenVideoCapture(deviceID)
webcam.Set(3, 640)
webcam.Set(4, 480)
if err != nil {
log.Println("Cannot open webcam")
return false
}
// We need to sleep a little so the image stabilizes before reading it
time.Sleep(1 * time.Second)
ok := webcam.Read(img)
webcam.Close()
if ok && !img.Empty() {
return true
}
log.Println("Cannot read image, sleeping for retry...")
time.Sleep(200 * time.Millisecond)
}
log.Println("Cannot read from webcam")
return false
}
func detectFaces(frame *gocv.Mat, results gocv.Mat) []detectedFace {
faces := make([]detectedFace, results.Total())
for i := 0; i < results.Total(); i += 7 {
faces[i].confidence = results.GetFloatAt(0, i+2)
faces[i].left = int(results.GetFloatAt(0, i+3) * float32(frame.Cols()))
faces[i].top = int(results.GetFloatAt(0, i+4) * float32(frame.Rows()))
faces[i].right = int(results.GetFloatAt(0, i+5) * float32(frame.Cols()))
faces[i].bottom = int(results.GetFloatAt(0, i+6) * float32(frame.Rows()))
}
return faces
}