hybridgroup.gobot/examples/ardrone_face_tracking.go

83 lines
1.9 KiB
Go
Raw Normal View History

// +build example
//
// Do not build by default.
package main
import (
"fmt"
"math"
"path"
"runtime"
"time"
2014-07-11 08:21:21 +08:00
cv "github.com/lazywei/go-opencv/opencv"
"gobot.io/x/gobot"
"gobot.io/x/gobot/platforms/opencv"
"gobot.io/x/gobot/platforms/parrot/ardrone"
)
func main() {
2014-06-09 10:50:15 +08:00
runtime.GOMAXPROCS(runtime.NumCPU())
_, currentfile, _, _ := runtime.Caller(0)
cascade := path.Join(path.Dir(currentfile), "haarcascade_frontalface_alt.xml")
window := opencv.NewWindowDriver()
camera := opencv.NewCameraDriver("tcp://192.168.1.1:5555")
ardroneAdaptor := ardrone.NewAdaptor()
drone := ardrone.NewDriver(ardroneAdaptor)
work := func() {
detect := false
drone.TakeOff()
var image *cv.IplImage
camera.On(opencv.Frame, func(data interface{}) {
image = data.(*cv.IplImage)
2016-07-13 23:32:22 +08:00
if !detect {
window.ShowImage(image)
}
})
drone.On(ardrone.Flying, func(data interface{}) {
gobot.After(1*time.Second, func() { drone.Up(0.2) })
gobot.After(2*time.Second, func() { drone.Hover() })
gobot.After(5*time.Second, func() {
detect = true
2014-06-09 10:50:15 +08:00
gobot.Every(300*time.Millisecond, func() {
drone.Hover()
i := image
2014-04-29 02:23:12 +08:00
faces := opencv.DetectFaces(cascade, i)
biggest := 0
var face *cv.Rect
for _, f := range faces {
if f.Width() > biggest {
biggest = f.Width()
face = f
}
}
if face != nil {
2014-06-09 10:50:15 +08:00
opencv.DrawRectangles(i, []*cv.Rect{face}, 0, 255, 0, 5)
2014-06-11 06:16:11 +08:00
centerX := float64(image.Width()) * 0.5
turn := -(float64(face.X()) - centerX) / centerX
fmt.Println("turning:", turn)
if turn < 0 {
drone.Clockwise(math.Abs(turn * 0.4))
} else {
drone.CounterClockwise(math.Abs(turn * 0.4))
}
}
window.ShowImage(i)
})
gobot.After(20*time.Second, func() { drone.Land() })
})
})
}
2014-07-09 09:36:14 +08:00
robot := gobot.NewRobot("face",
[]gobot.Connection{ardroneAdaptor},
[]gobot.Device{window, camera, drone},
work,
)
robot.Start()
}