gobot.io/x/gobot@v1.16.0/examples/opencv_face_detect.go (about)

     1  // +build example
     2  //
     3  // Do not build by default.
     4  
     5  package main
     6  
     7  import (
     8  	"path"
     9  	"runtime"
    10  	"sync/atomic"
    11  	"time"
    12  
    13  	"gobot.io/x/gobot"
    14  	"gobot.io/x/gobot/platforms/opencv"
    15  	"gocv.io/x/gocv"
    16  )
    17  
    18  var img atomic.Value
    19  
    20  func main() {
    21  	_, currentfile, _, _ := runtime.Caller(0)
    22  	cascade := path.Join(path.Dir(currentfile), "haarcascade_frontalface_alt.xml")
    23  
    24  	window := opencv.NewWindowDriver()
    25  	camera := opencv.NewCameraDriver(1)
    26  
    27  	work := func() {
    28  		mat := gocv.NewMat()
    29  		img.Store(mat)
    30  
    31  		camera.On(opencv.Frame, func(data interface{}) {
    32  			i := data.(gocv.Mat)
    33  			img.Store(i)
    34  		})
    35  
    36  		gobot.Every(10*time.Millisecond, func() {
    37  			i := img.Load().(gocv.Mat)
    38  			if i.Empty() {
    39  				return
    40  			}
    41  			faces := opencv.DetectObjects(cascade, i)
    42  			opencv.DrawRectangles(i, faces, 0, 255, 0, 5)
    43  			window.ShowImage(i)
    44  			window.WaitKey(1)
    45  		})
    46  	}
    47  
    48  	robot := gobot.NewRobot("faceBot",
    49  		[]gobot.Connection{},
    50  		[]gobot.Device{window, camera},
    51  		work,
    52  	)
    53  
    54  	robot.Start()
    55  }