-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetector.go
63 lines (52 loc) · 1.31 KB
/
detector.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
package faceapi
import (
"fmt"
"os"
"github.com/hybridgroup/go-opencv/opencv"
)
// Detector allows detecting objects in images.
type Detector struct {
cascade *opencv.HaarCascade
}
// Create new detector from supplied Haar classifier file.
func NewDetector(classifierFile string) (*Detector, error) {
// check if file exists
if st, err := os.Stat(classifierFile); os.IsNotExist(err) || st.IsDir() {
return nil, fmt.Errorf("Classifier file does not exist.")
}
cascade := opencv.LoadHaarClassifierCascade(classifierFile)
return &Detector{cascade: cascade}, nil
}
// Single point.
type Point struct {
X, Y int
}
// A rectangle.
type Rect struct {
A, B Point
}
type DetectorResult struct {
Objects []Rect
}
func resultFromRects(rects []*opencv.Rect) DetectorResult {
result := DetectorResult{}
for _, rect := range rects {
result.Objects = append(result.Objects,
Rect{
A: Point{rect.X(),
rect.Y()},
B: Point{rect.X() + rect.Width(),
rect.Y() + rect.Height()},
})
}
return result
}
func (d Detector) FindInFile(imageFile string) (DetectorResult, error) {
image := opencv.LoadImage(imageFile)
if image == nil {
return DetectorResult{}, fmt.Errorf("Failed to load image from file.")
}
defer image.Release()
rects := d.cascade.DetectObjects(image)
return resultFromRects(rects), nil
}