Skip to content

Instantly share code, notes, and snippets.

@shivakar
Created March 3, 2018 18:44
Show Gist options
  • Save shivakar/95ad08ecc3e2626d2c70f2b4bdfce6a4 to your computer and use it in GitHub Desktop.
Save shivakar/95ad08ecc3e2626d2c70f2b4bdfce6a4 to your computer and use it in GitHub Desktop.
Webcam streaming over HTTP
package main
import (
"flag"
"fmt"
"image"
"image/color"
"log"
"net/http"
"time"
"github.com/hybridgroup/mjpeg"
"gocv.io/x/gocv"
)
var (
deviceID = flag.Int("device", 0, "Device ID")
httpAddr = flag.String("http", "0.0.0.0:8080", "HTTP interface to stream on")
)
func main() {
webcam, err := gocv.VideoCaptureDevice(*deviceID)
if err != nil {
log.Fatalf("error opening video capture device: %v: %v", *deviceID, err)
}
defer webcam.Close()
webcam.Set(gocv.VideoCaptureFPS, 10.0)
stream := mjpeg.NewStream()
go func() {
img := gocv.NewMat()
defer img.Close()
for {
if ok := webcam.Read(img); !ok {
log.Println("error reading from video capture device")
return
}
if img.Empty() {
continue
}
ts := time.Now().Format("2006-01-02 13:04:05.000")
gocv.PutText(img, ts, image.Point{30, 30}, gocv.FontHersheyComplexSmall, 0.8, color.RGBA{0, 255, 0, 255}, 1)
frame, err := gocv.IMEncode(gocv.JPEGFileExt, img)
if err != nil {
log.Printf("error encoding frame: %v", err)
continue
}
stream.UpdateJPEG(frame)
}
}()
fmt.Printf("Streaming on %v...", *httpAddr)
http.Handle("/", stream)
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment