-
Notifications
You must be signed in to change notification settings - Fork 869
/
main.go
91 lines (75 loc) · 1.62 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// What it does:
//
// This example opens a video capture device, then streams MJPEG from it.
// Once running point your browser to the hostname/port you passed in the
// command line (for example http://localhost:8080) and you should see
// the live video stream.
//
// How to run:
//
// mjpeg-streamer [camera ID] [host:port]
//
// go get -u github.com/hybridgroup/mjpeg
// go run ./cmd/mjpeg-streamer/main.go 1 0.0.0.0:8080
//
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/hybridgroup/mjpeg"
"gocv.io/x/gocv"
)
var (
deviceID int
err error
webcam *gocv.VideoCapture
stream *mjpeg.Stream
)
func main() {
if len(os.Args) < 3 {
fmt.Println("How to run:\n\tmjpeg-streamer [camera ID] [host:port]")
return
}
// parse args
deviceID := os.Args[1]
host := os.Args[2]
// open webcam
webcam, err = gocv.OpenVideoCapture(deviceID)
if err != nil {
fmt.Printf("Error opening capture device: %v\n", deviceID)
return
}
defer webcam.Close()
// create the mjpeg stream
stream = mjpeg.NewStream()
// start capturing
go mjpegCapture()
fmt.Println("Capturing. Point your browser to " + host)
// start http server
http.Handle("/", stream)
server := &http.Server{
Addr: host,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
log.Fatal(server.ListenAndServe())
}
func mjpegCapture() {
img := gocv.NewMat()
defer img.Close()
for {
if ok := webcam.Read(&img); !ok {
fmt.Printf("Device closed: %v\n", deviceID)
return
}
if img.Empty() {
continue
}
buf, _ := gocv.IMEncode(".jpg", img)
stream.UpdateJPEG(buf.GetBytes())
buf.Close()
}
}