-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.go
88 lines (73 loc) · 1.63 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
package main
import (
"fmt"
"html/template"
"image"
"log"
"net/http"
"os"
"sync"
"time"
"gocv.io/x/gocv"
)
var (
err error
webcam *gocv.VideoCapture
frame_id int
)
var buffer = make(map[int][]byte)
var frame []byte
var mutex = &sync.Mutex{}
func main() {
host := "0.0.0.0:3000"
// open webcam
if len(os.Args) < 2 {
fmt.Println(">> device /dev/video0 (default)")
webcam, err = gocv.VideoCaptureDevice(0)
} else {
fmt.Println(">> file/url :: " + os.Args[1])
webcam, err = gocv.VideoCaptureFile(os.Args[1])
}
if err != nil {
fmt.Printf("Error opening capture device: \n")
return
}
defer webcam.Close()
// start capturing
go getframes()
fmt.Println("Capturing. Open http://" + host)
// start http server
http.HandleFunc("/video", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary=frame")
data := ""
for {
/* fmt.Println("Frame ID: ", frame_id)
*/mutex.Lock()
data = "--frame\r\n Content-Type: image/jpeg\r\n\r\n" + string(frame) + "\r\n\r\n"
mutex.Unlock()
time.Sleep(33 * time.Millisecond)
w.Write([]byte(data))
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("index.html")
t.Execute(w, "index")
})
log.Fatal(http.ListenAndServe(host, nil))
}
func getframes() {
img := gocv.NewMat()
defer img.Close()
for {
if ok := webcam.Read(&img); !ok {
fmt.Printf("Device closed\n")
return
}
if img.Empty() {
continue
}
frame_id++
gocv.Resize(img, &img, image.Point{}, float64(0.5), float64(0.5), 0)
frame, _ = gocv.IMEncode(".jpg", img)
}
}