-
Notifications
You must be signed in to change notification settings - Fork 870
/
main.go
111 lines (86 loc) · 2.41 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// What it does:
//
// This example detects motion using a delta threshold from the first frame,
// and then finds contours to determine where the object is located.
//
// Very loosely based on Adrian Rosebrock code located at:
// http://www.pyimagesearch.com/2015/06/01/home-surveillance-and-motion-detection-with-the-raspberry-pi-python-and-opencv/
//
// How to run:
//
// go run ./cmd/motion-detect/main.go 0
//
package main
import (
"fmt"
"image"
"image/color"
"os"
"gocv.io/x/gocv"
)
const MinimumArea = 3000
func main() {
if len(os.Args) < 2 {
fmt.Println("How to run:\n\tmotion-detect [camera ID]")
return
}
// parse args
deviceID := os.Args[1]
webcam, err := gocv.OpenVideoCapture(deviceID)
if err != nil {
fmt.Printf("Error opening video capture device: %v\n", deviceID)
return
}
defer webcam.Close()
window := gocv.NewWindow("Motion Window")
defer window.Close()
img := gocv.NewMat()
defer img.Close()
imgDelta := gocv.NewMat()
defer imgDelta.Close()
imgThresh := gocv.NewMat()
defer imgThresh.Close()
mog2 := gocv.NewBackgroundSubtractorMOG2()
defer mog2.Close()
status := "Ready"
fmt.Printf("Start reading device: %v\n", deviceID)
for {
if ok := webcam.Read(&img); !ok {
fmt.Printf("Device closed: %v\n", deviceID)
return
}
if img.Empty() {
continue
}
status = "Ready"
statusColor := color.RGBA{0, 255, 0, 0}
// first phase of cleaning up image, obtain foreground only
mog2.Apply(img, &imgDelta)
// remaining cleanup of the image to use for finding contours.
// first use threshold
gocv.Threshold(imgDelta, &imgThresh, 25, 255, gocv.ThresholdBinary)
// then dilate
kernel := gocv.GetStructuringElement(gocv.MorphRect, image.Pt(3, 3))
gocv.Dilate(imgThresh, &imgThresh, kernel)
kernel.Close()
// now find contours
contours := gocv.FindContours(imgThresh, gocv.RetrievalExternal, gocv.ChainApproxSimple)
for i := 0; i < contours.Size(); i++ {
area := gocv.ContourArea(contours.At(i))
if area < MinimumArea {
continue
}
status = "Motion detected"
statusColor = color.RGBA{255, 0, 0, 0}
gocv.DrawContours(&img, contours, i, statusColor, 2)
rect := gocv.BoundingRect(contours.At(i))
gocv.Rectangle(&img, rect, color.RGBA{0, 0, 255, 0}, 2)
}
contours.Close()
gocv.PutText(&img, status, image.Pt(10, 20), gocv.FontHersheyPlain, 1.2, statusColor, 2)
window.IMShow(img)
if window.WaitKey(1) == 27 {
break
}
}
}