Grabbing an image from the webcam 

First, we'll open a connection to the webcam:

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

Here, I used VideoCaptureDevice(0) because, on my computer, which runs Ubuntu, the webcam is device 0. Your webcam may differ in device numbering. Also, do note defer webcam.Close(). This is the aforementioned resource metaphor that GoCV sticks very strongly to. A webcam (specifically, a VideoCaptureDevice) is a resource, much like a file. In fact in Linux, this is true; the webcam on my computer is mounted in the /dev/video0 directory and I can access raw bytes from it by just using a variant of cat. But I digress. The point is that .Close() has to be called on resources to free up usage.


The talk about closing resources to free up usage naturally raises a question, given we program in Go. Is a channel a resource? The answer is no. close(ch) of a channel  merely informs every sender that this channel is no longer receiving data.

Having access to the webcam is nice and all, but we also want to be able to grab images off it. I had mentioned one can read raw streams off the file of a webcam. We can do the same with GoCV as well:

```
img := gocv.NewMat()
defer img.Close()
width := int(webcam.Get(gocv.VideoCaptureFrameWidth))
height := int(webcam.Get(gocv.VideoCaptureFrameHeight))
fmt.Printf("Webcam resolution: %v, %v", width, height)
if ok := webcam.Read(&img); !ok {
log.Fatal("cannot read device 0")
}
```

First, we create a new matrix, representing an image. Again, the matrix is treated like a resource, because it is owned by the foreign function interface. Thus, defer img.Close() is written. Next, we query the webcam for information about the resolution. This is not as important right now, but it will be later. Nonetheless, it's quite nice to know what resolution a webcam runs at. Last, we read the webcam's image into the matrix.

At this point, if you are already familiar with Gorgonia's tensor libraries, this pattern may seem familiar, and yet feels funny. img := gocv.NewMat() does not define a size. How does GoCV know how much space to allocate for the matrix? Well, the answer is that the magic happens in webcam.Read. The underlying matrix will be resized as necessary by OpenCV. In this way, the Go part of the program does no real memory allocation.

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

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