forked from therecipe/qt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gocv.go
96 lines (75 loc) · 1.94 KB
/
gocv.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
package main
import (
"github.com/dsandor/qt/core"
"github.com/dsandor/qt/gui"
"github.com/dsandor/qt/quick"
"fmt"
"gocv.io/x/gocv"
"image"
"image/color"
"sync"
)
func init() {
GoCV_QmlRegisterType2("CustomModule", 1, 0, "GoCV")
}
type GoCV struct {
quick.QQuickPaintedItem
_ func() `constructor:"init"`
_ bool `property:"detect"`
image *gui.QImage
data []byte
mutex *sync.Mutex
}
func (p *GoCV) init() {
p.SetDetect(false)
xmlFile := "./facedetect.xml"
//setup gocv
webcam, _ := gocv.OpenVideoCapture(0)
// prepare image matrix
img := gocv.NewMat()
//setup painting
p.image = gui.NewQImage()
p.mutex = new(sync.Mutex)
p.SetRenderTarget(quick.QQuickPaintedItem__FramebufferObject)
p.ConnectPaint(p.paint)
// color for the rect when faces detected
blue := color.RGBA{0, 0, 255, 0}
// load classifier to recognize faces
classifier := gocv.NewCascadeClassifier()
if !classifier.Load(xmlFile) {
fmt.Printf("Error reading cascade file: %v\n", xmlFile)
return
}
go func() {
for {
webcam.Read(&img)
if img.Empty() {
fmt.Println("empty, continuing")
continue
}
p.mutex.Lock()
if p.IsDetect() {
// detect faces
rects := classifier.DetectMultiScale(img)
fmt.Printf("found %d faces\n", len(rects))
// draw a rectangle around each face on the original image,
// along with text identifing as "Human"
for _, r := range rects {
gocv.Rectangle(&img, r, blue, 3)
size := gocv.GetTextSize("Human", gocv.FontHersheyPlain, 1.2, 2)
pt := image.Pt(r.Min.X+(r.Min.X/2)-(size.X/2), r.Min.Y-2)
gocv.PutText(&img, "Human", pt, gocv.FontHersheyPlain, 1.2, blue, 2)
}
}
p.data, _ = gocv.IMEncode(".jpg", img)
p.mutex.Unlock()
p.Update()
}
}()
}
func (p *GoCV) paint(painter *gui.QPainter) {
p.mutex.Lock()
p.image.LoadFromData(p.data, len(p.data), "JPG")
p.mutex.Unlock()
painter.DrawImage6(core.NewQRect4(0, 0, int(p.Width()), int(p.Height())), p.image)
}