-
Notifications
You must be signed in to change notification settings - Fork 6
/
motiondetector.py
80 lines (61 loc) · 1.96 KB
/
motiondetector.py
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
import numpy as np
import cv2
class MotionDetector:
def __init__(self):
self.bgsubtractor = cv2.bgsegm.createBackgroundSubtractorMOG()
self.firstObserv = True
self.prob = 0
self.motion = False
def gaussianfilter(self,inputImg):
return cv2.GaussianBlur(inputImg,(15,15),0)
def medianblur(self,inputImg):
return cv2.medianBlur(inputImg,5)
def threshold(self,inputImg):
_,result = cv2.threshold(inputImg,10,255,cv2.THRESH_BINARY)
return result
def calculate_movement(self,inputImg):
height, width = inputImg.shape
area = height*width
activepixels = cv2.countNonZero(inputImg)
motionPercentage = (activepixels / area)*100
if motionPercentage > 0.5:
self.motion = True
else:
self.motion = False
def bayesianclassifier(self):
'''
Bayesian Classifier
Input Args: boolean moved or not
Output Args: probability of movement
---------------------------------------------------------------
probability of motion: 0.5
probability of observed motion given there is motion: 0.8
probability of observed motion given there is no motion: 0.1
probability of no observed motion given there is motion 0.1
probability of no observed motion given there is no motion 0.8
---------------------------------------------------------------
'''
if self.firstObserv:
if self.motion:
self.prob = (0.8*0.5)/0.9
else:
self.prob = (0.1*0.5)/0.9
self.firstObserv = False
else:
if self.motion:
self.prob = (0.8*self.prob)/( (0.8*self.prob) + 0.1*(1-self.prob))
else:
self.prob = (0.1*self.prob)/( (0.1*self.prob) + 0.8*(1-self.prob))
# simple boundary setting
if self.prob > 0.6:
self.prob = 0.6
if self.prob < 0.1:
self.prob = 0.1
def detectmotion(self, inputImg):
step1 = self.medianblur(inputImg)
step2 = self.bgsubtractor.apply(step1)
step3 = self.gaussianfilter(step2)
step4 = self.threshold(step3)
self.calculate_movement(step4)
self.bayesianclassifier()
return self.prob > 0.5