1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-29 13:49:14 +08:00

80 lines
1.6 KiB
Go
Raw Normal View History

2014-04-27 16:58:34 -07:00
package opencv
import (
2014-11-19 15:59:17 -08:00
"errors"
"gobot.io/x/gobot"
"gocv.io/x/gocv"
2014-04-27 16:58:34 -07:00
)
type capture interface {
Read(img *gocv.Mat) bool
}
const (
// Frame event
Frame = "frame"
)
// CameraDriver is the Gobot Driver for the OpenCV camera
2014-04-27 16:58:34 -07:00
type CameraDriver struct {
name string
camera capture
Source interface{}
start func(*CameraDriver) (err error)
gobot.Eventer
2014-04-27 16:58:34 -07:00
}
// NewCameraDriver creates a new driver with specified source.
// It also creates a start function to either set camera as a File or Camera capture.
func NewCameraDriver(source interface{}) *CameraDriver {
2014-07-07 17:31:35 -07:00
c := &CameraDriver{
name: "Camera",
Eventer: gobot.NewEventer(),
Source: source,
2014-11-19 15:59:17 -08:00
start: func(c *CameraDriver) (err error) {
2014-07-23 16:38:46 -07:00
switch v := c.Source.(type) {
case string:
c.camera, _ = gocv.VideoCaptureFile(v)
2014-07-23 16:38:46 -07:00
case int:
c.camera, _ = gocv.VideoCaptureDevice(v)
2014-07-23 16:38:46 -07:00
default:
2014-11-19 15:59:17 -08:00
return errors.New("Unknown camera source")
2014-07-23 16:38:46 -07:00
}
2014-11-19 15:59:17 -08:00
return
2014-07-23 16:38:46 -07:00
},
2014-04-27 16:58:34 -07:00
}
2014-07-07 17:31:35 -07:00
c.AddEvent(Frame)
2014-07-07 17:31:35 -07:00
return c
2014-04-27 16:58:34 -07:00
}
// Name returns the Driver name
func (c *CameraDriver) Name() string { return c.name }
// SetName sets the Driver name
func (c *CameraDriver) SetName(n string) { c.name = n }
// Connection returns the Driver's connection
func (c *CameraDriver) Connection() gobot.Connection { return nil }
// Start initializes camera by grabbing frames
func (c *CameraDriver) Start() (err error) {
if err := c.start(c); err != nil {
return err
2014-11-19 15:59:17 -08:00
}
img := gocv.NewMat()
2014-11-16 10:32:51 -08:00
go func() {
for {
if ok := c.camera.Read(&img); ok {
c.Publish(Frame, img)
2014-04-27 16:58:34 -07:00
}
}
2014-11-16 10:32:51 -08:00
}()
2014-11-20 17:54:48 -08:00
return
2014-04-27 16:58:34 -07:00
}
// Halt stops camera driver
func (c *CameraDriver) Halt() (err error) { return }