-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathyolov3_test.go
504 lines (463 loc) · 14.1 KB
/
yolov3_test.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package yolov3
import (
"fmt"
"image"
"os"
"path"
"testing"
"github.com/golang/mock/gomock"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/suite"
"gocv.io/x/gocv"
"github.com/wimspaargaren/yolov3/internal/ml"
"github.com/wimspaargaren/yolov3/internal/ml/mocks"
)
type YoloTestSuite struct {
suite.Suite
}
func TestYoloTestSuite(t *testing.T) {
suite.Run(t, new(YoloTestSuite))
}
func (s *YoloTestSuite) TestCorrectImplementation() {
var _ Net = &yoloNet{}
}
func (s *YoloTestSuite) TestNewDefaultNetCorrectCreation() {
net, err := NewNet("data/yolov3/yolov3.weights", "data/yolov3/yolov3.cfg", "data/yolov3/coco.names")
s.Require().NoError(err)
yoloNet := net.(*yoloNet)
s.NotNil(yoloNet.net)
s.Equal(81, len(yoloNet.cocoNames))
s.Equal(DefaultInputWidth, yoloNet.DefaultInputWidth)
s.Equal(DefaultInputHeight, yoloNet.DefaultInputHeight)
s.Equal(DefaultConfThreshold, yoloNet.confidenceThreshold)
s.Equal(DefaultNMSThreshold, yoloNet.DefaultNMSThreshold)
s.NoError(yoloNet.Close())
}
func (s *YoloTestSuite) TestNewCustomConfig_MissingNewNetFunc_CorrectCreation() {
net, err := NewNetWithConfig("data/yolov3/yolov3.weights", "data/yolov3/yolov3.cfg", "data/yolov3/coco.names", Config{})
s.Require().NoError(err)
yoloNet := net.(*yoloNet)
s.NotNil(yoloNet.net)
s.Equal(81, len(yoloNet.cocoNames))
s.Equal(DefaultInputWidth, yoloNet.DefaultInputWidth)
s.Equal(DefaultInputHeight, yoloNet.DefaultInputHeight)
s.Equal(float32(0), yoloNet.confidenceThreshold)
s.Equal(float32(0), yoloNet.DefaultNMSThreshold)
s.NoError(yoloNet.Close())
}
func (s *YoloTestSuite) TestUnableTocCreateNewNet() {
tests := []struct {
Name string
WeightsPath string
ConfigPath string
CocoNamePath string
Config Config
Error error
SetupNeuralNetMock func() *mocks.MockNeuralNet
}{
{
Name: "Non existent weights path",
WeightsPath: "data/yolov3/notexistent",
ConfigPath: "data/yolov3/yolov3.cfg",
CocoNamePath: "data/yolov3/coco.names",
Error: fmt.Errorf("path to net weights not found"),
},
{
Name: "Non existent config path",
WeightsPath: "data/yolov3/yolov3.weights",
ConfigPath: "data/yolov3/notexistent",
CocoNamePath: "data/yolov3/coco.names",
Error: fmt.Errorf("path to net config not found"),
},
{
Name: "Non existent coco names path",
WeightsPath: "data/yolov3/yolov3.weights",
ConfigPath: "data/yolov3/yolov3.cfg",
CocoNamePath: "data/yolov3/notexistent",
},
{
Name: "Unable to set preferable backend",
WeightsPath: "data/yolov3/yolov3.weights",
ConfigPath: "data/yolov3/yolov3.cfg",
CocoNamePath: "data/yolov3/coco.names",
SetupNeuralNetMock: func() *mocks.MockNeuralNet {
controller := gomock.NewController(s.T())
neuralNetMock := mocks.NewMockNeuralNet(controller)
neuralNetMock.EXPECT().SetPreferableBackend(gomock.Any()).Return(fmt.Errorf("very broken")).Times(1)
return neuralNetMock
},
Error: fmt.Errorf("very broken"),
},
{
Name: "Unable to set preferable target type",
WeightsPath: "data/yolov3/yolov3.weights",
ConfigPath: "data/yolov3/yolov3.cfg",
CocoNamePath: "data/yolov3/coco.names",
SetupNeuralNetMock: func() *mocks.MockNeuralNet {
controller := gomock.NewController(s.T())
neuralNetMock := mocks.NewMockNeuralNet(controller)
neuralNetMock.EXPECT().SetPreferableBackend(gomock.Any()).Return(nil).Times(1)
neuralNetMock.EXPECT().SetPreferableTarget(gomock.Any()).Return(fmt.Errorf("very broken")).Times(1)
return neuralNetMock
},
Error: fmt.Errorf("very broken"),
},
}
for _, test := range tests {
s.Run(test.Name, func() {
test.Config.NewNet = func(string, string) ml.NeuralNet {
return test.SetupNeuralNetMock()
}
_, err := NewNetWithConfig(test.WeightsPath, test.ConfigPath, test.CocoNamePath, test.Config)
s.Error(err)
if test.Error != nil {
s.Equal(test.Error, err)
}
})
}
}
func (s *YoloTestSuite) TestClassIDAndConfidence() {
tests := []struct {
Name string
Input []float32
ExpectedIndex int
ExpetedConfidence float32
}{
{
Name: "no inputs",
ExpectedIndex: 0,
ExpetedConfidence: 0,
},
{
Name: "single inputs",
Input: []float32{99.9},
ExpectedIndex: 0,
ExpetedConfidence: 99.9,
},
{
Name: "single inputs",
Input: []float32{70.0, 99.9},
ExpectedIndex: 1,
ExpetedConfidence: 99.9,
},
{
Name: "single inputs",
Input: []float32{99.9, 70.0},
ExpectedIndex: 0,
ExpetedConfidence: 99.9,
},
}
for _, test := range tests {
s.Run(test.Name, func() {
index, confidence := getClassIDAndConfidence(test.Input)
s.Equal(test.ExpectedIndex, index)
s.Equal(test.ExpetedConfidence, confidence)
})
}
}
func (s *YoloTestSuite) TestCalculateBoundingBox() {
tests := []struct {
Name string
InputFrame gocv.Mat
InputRow []float32
ExpectedRect image.Rectangle
}{
{
Name: "normal bounding box calculation",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputRow: []float32{1, 1, 1, 1},
ExpectedRect: image.Rect(1, 1, 3, 3),
},
{
Name: "unexpected row",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputRow: []float32{1, 1, 1},
ExpectedRect: image.Rect(0, 0, 0, 0),
},
}
for _, test := range tests {
s.Run(test.Name, func() {
rect := calculateBoundingBox(test.InputFrame, test.InputRow)
s.Equal(test.ExpectedRect, rect)
})
}
}
func (s *YoloTestSuite) TestIsFiltered() {
tests := []struct {
Name string
ClassID int
ClassIDs map[string]bool
Expected bool
}{
{
Name: "no inputs",
Expected: false,
},
{
Name: "is filtered",
ClassID: 1,
ClassIDs: map[string]bool{"coffee": true},
Expected: true,
},
{
Name: "is not filtered",
ClassID: 0,
ClassIDs: map[string]bool{"coffee": true},
Expected: false,
},
}
for _, test := range tests {
s.Run(test.Name, func() {
y := &yoloNet{
cocoNames: []string{"laptop", "coffee"},
}
s.Equal(test.Expected, y.isFiltered(test.ClassID, test.ClassIDs))
})
}
}
func (s *YoloTestSuite) TestProcessOutputs() {
tests := []struct {
Name string
InputFrame gocv.Mat
InputOutputs []gocv.Mat
InputFilter map[string]bool
InputConfidenceThreshHold float32
Result []ObjectDetection
ExpectError bool
}{
{
Name: "Two rows containing two predictions",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputOutputs: func() []gocv.Mat {
laptopDetection := laptopDetection()
coffeeDetection := coffeeDetection()
return []gocv.Mat{laptopDetection, coffeeDetection}
}(),
InputFilter: map[string]bool{},
Result: []ObjectDetection{
{
ClassID: 0,
Confidence: 9,
ClassName: "laptop",
BoundingBox: image.Rect(1, 1, 3, 3),
},
{
ClassID: 1,
Confidence: 9,
ClassName: "coffee",
BoundingBox: image.Rect(-1, 1, 1, 3),
},
},
},
{
Name: "Incorrect input layer provided",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputOutputs: func() []gocv.Mat {
return []gocv.Mat{gocv.NewMatWithSize(1, 10, gocv.MatTypeCV16S)}
}(),
ExpectError: true,
},
{
Name: "Result was filtered",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputOutputs: func() []gocv.Mat {
coffeeDetection := coffeeDetection()
return []gocv.Mat{coffeeDetection}
}(),
InputFilter: map[string]bool{"coffee": true},
Result: []ObjectDetection{},
},
{
Name: "Confidence not high enough",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputOutputs: func() []gocv.Mat {
coffeeDetection := coffeeDetection()
return []gocv.Mat{coffeeDetection}
}(),
InputConfidenceThreshHold: 999,
InputFilter: map[string]bool{"coffee": true},
Result: []ObjectDetection{},
},
{
Name: "Filter overlapping frame",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
InputOutputs: func() []gocv.Mat {
coffeeDetection1 := coffeeDetection()
coffeeDetection2 := coffeeDetection()
coffeeDetection2.SetFloatAt(0, 6, 10)
return []gocv.Mat{coffeeDetection1, coffeeDetection2}
}(),
InputFilter: map[string]bool{},
Result: []ObjectDetection{
{
ClassID: 1,
Confidence: 10,
ClassName: "coffee",
BoundingBox: image.Rect(-1, 1, 1, 3),
},
},
},
}
for _, test := range tests {
s.Run(test.Name, func() {
y := &yoloNet{
cocoNames: []string{"laptop", "coffee"},
confidenceThreshold: test.InputConfidenceThreshHold,
}
detections, err := y.processOutputs(test.InputFrame, test.InputOutputs, test.InputFilter)
if test.ExpectError {
s.Error(err)
} else {
s.Require().NoError(err)
}
s.Equal(test.Result, detections)
})
}
}
func (s *YoloTestSuite) TestGetDetections() {
tests := []struct {
Name string
InputFrame gocv.Mat
InputConfidenceThreshHold float32
Result []ObjectDetection
ExpectError bool
SetupNeuralNetMock func() *mocks.MockNeuralNet
Panics bool
}{
{
Name: "Get successful detection",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
SetupNeuralNetMock: func() *mocks.MockNeuralNet {
controller := gomock.NewController(s.T())
neuralNetMock := mocks.NewMockNeuralNet(controller)
neuralNetMock.EXPECT().SetInput(gomock.Any(), "data").Times(1)
neuralNetMock.EXPECT().ForwardLayers(gomock.Any()).Return(func() []gocv.Mat {
laptopDetection := laptopDetection()
coffeeDetection := coffeeDetection()
return []gocv.Mat{laptopDetection, coffeeDetection}
}()).Times(1)
return neuralNetMock
},
Result: []ObjectDetection{
{
ClassID: 0,
Confidence: 9,
ClassName: "laptop",
BoundingBox: image.Rect(1, 1, 3, 3),
},
{
ClassID: 1,
Confidence: 9,
ClassName: "coffee",
BoundingBox: image.Rect(-1, 1, 1, 3),
},
},
},
{
Name: "Incorrect input layer provided",
InputFrame: gocv.NewMatWithSize(2, 2, gocv.MatTypeCV32F),
SetupNeuralNetMock: func() *mocks.MockNeuralNet {
controller := gomock.NewController(s.T())
neuralNetMock := mocks.NewMockNeuralNet(controller)
neuralNetMock.EXPECT().SetInput(gomock.Any(), "data").Times(1)
neuralNetMock.EXPECT().ForwardLayers(gomock.Any()).Return([]gocv.Mat{gocv.NewMatWithSize(1, 10, gocv.MatTypeCV16S)}).Times(1)
return neuralNetMock
},
ExpectError: true,
},
}
for _, test := range tests {
s.Run(test.Name, func() {
y := &yoloNet{
cocoNames: []string{"laptop", "coffee"},
confidenceThreshold: test.InputConfidenceThreshHold,
net: test.SetupNeuralNetMock(),
}
if test.Panics {
s.Panics(func() { y.GetDetections(test.InputFrame) })
} else {
detections, err := y.GetDetections(test.InputFrame)
if test.ExpectError {
s.Error(err)
} else {
s.Require().NoError(err)
}
s.Equal(test.Result, detections)
}
})
}
}
func laptopDetection() gocv.Mat {
laptopDetection := gocv.NewMatWithSize(1, 10, gocv.MatTypeCV32F)
laptopDetection.SetFloatAt(0, 0, 1)
laptopDetection.SetFloatAt(0, 1, 1)
laptopDetection.SetFloatAt(0, 2, 1)
laptopDetection.SetFloatAt(0, 3, 1)
// Index for laptop == 5
laptopDetection.SetFloatAt(0, 5, 9)
return laptopDetection
}
func coffeeDetection() gocv.Mat {
coffeeDetection := gocv.NewMatWithSize(1, 10, gocv.MatTypeCV32F)
coffeeDetection.SetFloatAt(0, 1, 1)
coffeeDetection.SetFloatAt(0, 2, 1)
coffeeDetection.SetFloatAt(0, 3, 1)
coffeeDetection.SetFloatAt(0, 3, 1)
// Index for coffee == 6
coffeeDetection.SetFloatAt(0, 6, 9)
return coffeeDetection
}
func ExampleNewNet() {
yolov3WeightsPath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/data/yolov3/yolov3.weights")
yolov3ConfigPath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/data/yolov3/yolov3.cfg")
cocoNamesPath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/data/yolov3/coco.names")
yolonet, err := NewNet(yolov3WeightsPath, yolov3ConfigPath, cocoNamesPath)
if err != nil {
log.WithError(err).Fatal("unable to create yolo net")
}
// Gracefully close the net when the program is done
defer func() {
err := yolonet.Close()
if err != nil {
log.WithError(err).Error("unable to gracefully close yolo net")
}
}()
imagePath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/yolov3/data/example_images/bird.jpg")
frame := gocv.IMRead(imagePath, gocv.IMReadColor)
detections, err := yolonet.GetDetections(frame)
if err != nil {
log.WithError(err).Fatal("unable to retrieve predictions")
}
DrawDetections(&frame, detections)
window := gocv.NewWindow("Result Window")
defer func() {
err := window.Close()
if err != nil {
log.WithError(err).Error("unable to close window")
}
}()
window.IMShow(frame)
window.ResizeWindow(872, 585)
window.WaitKey(10000000000)
}
func ExampleNewNetWithConfig() {
yolov3WeightsPath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/data/yolov3/yolov3.weights")
yolov3ConfigPath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/data/yolov3/yolov3.cfg")
cocoNamesPath := path.Join(os.Getenv("GOPATH"), "src/github.com/wimspaargaren/data/yolov3/coco.names")
conf := DefaultConfig()
// Set the neural net to use CUDA
conf.NetBackendType = gocv.NetBackendCUDA
conf.NetTargetType = gocv.NetTargetCUDA
yolonet, err := NewNetWithConfig(yolov3WeightsPath, yolov3ConfigPath, cocoNamesPath, conf)
if err != nil {
log.WithError(err).Fatal("unable to create yolo net")
}
// Gracefully close the net when the program is done
defer func() {
err := yolonet.Close()
if err != nil {
log.WithError(err).Error("unable to gracefully close yolo net")
}
}()
// ...
}