Fork me on GitHub

使用GoCV进行人脸检测

示例代码:

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
package main

import (
"fmt"
"gocv.io/x/gocv"
"image"
"image/color"
"log"
)

func main() {
webCam , err := gocv.VideoCaptureDevice(0)
if err != nil {
log.Fatal(err)
}

defer webCam.Close()

window := gocv.NewWindow("face")
defer window.Close()

img := gocv.NewMat()
defer img.Close()

classifier := gocv.NewCascadeClassifier()
defer classifier.Close()

if !classifier.Load("/data/haarcascade_frontalface_default.xml")
{
log.Fatal("load model failed\n")
}

for {
if ok := webCam.Read(&img); !ok {
log.Fatalln("read img from webcam failed")
}

if img.Empty() {
continue
}

rects := classifier.DetectMultiScale(img)
fmt.Printf("found %d face\n",len(rects))

for _ , ret := range rects {
color := color.RGBA{0,0,225,0}
gocv.Rectangle(&img, ret, color,3)

size := gocv.GetTextSize("human",gocv.FontHersheyPlain, 1.2, 2)
pt := image.Pt(ret.Min.X+(ret.Min.X/2)-(size.X/2), ret.Min.Y-2)
gocv.PutText(&img, "Human", pt, gocv.FontHersheyPlain, 1.2, color, 2)
}

window.IMShow(img)
if window.WaitKey(1) & 0xff == int('q') {
break
}
}
}

编译

1
$go build test_face_detection.go

执行结果:

按q键,退出

您的鼓励是我持之以恒的动力