Reading from the Webcam 

By this point, I hope you have already read the previous chapter and have GoCV installed. If you haven't, then read the GoCV section in the previous chapter to get started.

To read from the webcam, we simply add the following lines to the main file. You may recognize them as snippets from the previous chapter:

     // open webcam
webcam, err := gocv.VideoCaptureDevice(0)
if err != nil {
log.Fatal(err)
}
defer webcam.Close()

// prepare image matrix
img := gocv.NewMat()
defer img.Close()

if ok := webcam.Read(&img); !ok {
log.Fatal("Failed to read image")
}

The confusing bit of course, is how to pass  img, which is of the gocv.Mat type, to MachineBox. There exists a Check method on the MachineBox client that takes io.Reader. img has a method, ToBytes, that returns a slice of bytes; coupled with bytes.NewReader, one should be able to easily pass io.Reader into Check.

But if you try that, it won't work.

Here's why: MachineBox expects an input that is formatted as a JPEG or PNG. If it is not, you will get a 400 Bad Request error. Poorly-formatted images would also cause these sorts of problems, which is why the error returned by box.Teach() is purposefully unhandled in the preceding line. In real-life settings, one might want to actually check whether it's a 400 Bad Request error that was returned.

The raw bytes of an image in img are not encoded as a known image format. Instead, we have to encode the image in img as a JPEG or a PNG and then pass it into MachineBox, as follows:

     var buf bytes.Buffer
prop, _ := img.ToImage()
if err = jpeg.Encode(&buf, prop, nil); err != nil {
log.Fatal("Failed to encode image as JPG %v", err)
}

faces, err := box.Check(&buf)
fmt.Printf("Error: %v ", err)
fmt.Printf("%#v", faces)

Here, we make use of the fact that *bytes.Buffer acts as both io.Reader and io.Writer. This way, we don't have to write directly to the file—rather, everything stays in memory.

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

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