Face detection 1 

The first face detection algorithm we want to use is the Viola-Jones method. It comes built into GoCV, so we can just use that. The consistency of GoCV gives us a hint as to what to do next. We need a classifier object (and remember to close it!)

This is how to create a classifier object:

```
classifier := gocv.NewCascadeClassifier()
if !classifier.Load(haarCascadeFile) {
log.Fatalf("Error reading cascade file: %v ", haarCascadeFile)
}
defer classifier.Close()
```

Note that at this point, it is not enough to just create a classifier. We need to load it with the model to use. The model used is very well established. It was first created by Rainer Lienhart in the early 2000s. Like most products of the 2000s, the model is serialized as an XML file.

The file can be downloaded from the GoCV GitHub repository: https://github.com/hybridgroup/gocv/blob/master/data/haarcascade_frontalface_default.xml

In the preceding code, haarCascadeFile is a string denoting the path to the file. GoCV handles the rest.

To detect faces, it is a simple one-liner:

```
rects := classifier.DetectMultiScale(img)
```

In this single line of code, we are telling OpenCV to use Viola-Jones' multiscale detection to detect faces. Internally, OpenCV builds an image pyramid of integral images, and runs the classifiers on the image pyramids. At each stage, rectangles representing where the algorithm thinks the faces are, produced. These rectangles are what is returned. They can then be drawn on the image before being output to a file or window.

Here's what a full windowed pipeline looks like:

```
var haarCascadeFile = "Path/To/CascadeFile.xml"
var blue = color.RGBA{0, 0, 255, 0}
func main() {
// open webcam
webcam, err := gocv.VideoCaptureDevice(0)
if err != nil {
log.Fatal(err)
}
defer webcam.Close()
var err error
// open display window
window := gocv.NewWindow("Face Detect")
defer window.Close()
// prepare image matrix
img := gocv.NewMat()
defer img.Close()
// color for the rect when faces detected
// load classifier to recognize faces
classifier := gocv.NewCascadeClassifier()
if !classifier.Load(haarCascadeFile) {
log.Fatalf("Error reading cascade file: %v ", haarCascadeFile)
}
defer classifier.Close()
for {
if ok := webcam.Read(&img); !ok {
fmt.Printf("cannot read device %d ", deviceID)
return
}
if img.Empty() {
continue
}
rects := classifier.DetectMultiScale(img)
for _, r := range rects {
gocv.Rectangle(&img, r, blue, 3)
}
window.IMShow(img)
if window.WaitKey(1) >= 0 {
break
}
}
}

```

The program is now able to get an image from the webcam, detect faces, draw rectangles around the faces, and then display the image. You may note that it is quite quick at doing that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.93.141