1
+ import cv2
2
+ import numpy as np
3
+
4
+ class Detection (object ):
5
+
6
+ THRESHOLD = 1500
7
+
8
+ def __init__ (self , image ):
9
+
10
+ #converting input color to black and white for easier processing
11
+ self .previous_gray = cv2 .cvtColor (image , cv2 .COLOR_BGR2GRAY )
12
+
13
+ def active_div (self , image ):
14
+
15
+ #obtain a new input image array
16
+ current_gray = cv2 .cvtColor (image , cv2 .COLOR_BGR2GRAY )
17
+
18
+ #find difference between previous and current image arrays
19
+ delta = cv2 .absdiff (self .previous_gray , current_gray )
20
+
21
+ #any pixels with value greater than 25 is replaced by 255
22
+ threshold_image = cv2 .threshold (delta , 25 , 255 , cv2 .THRESH_BINARY )[1 ]
23
+
24
+ cv2 .imshow ('OpenCV Detection' , image )
25
+ cv2 .waitKey (10 )
26
+
27
+ #storing new image
28
+ self .previous_gray = current_gray
29
+
30
+ # set cell width
31
+ h , w = threshold_image .shape [:2 ]
32
+ cell_width = w // 7
33
+
34
+ #storing the range in which the delta value exists (according to image divisions and octaves)
35
+ cells = np .array ([0 , 0 , 0 , 0 , 0 , 0 , 0 ])
36
+ #splitting the threshold image previously obtained into 7 divisions
37
+ #the countNonZero function returns the number of non-zero elements in division
38
+ cells [0 ] = cv2 .countNonZero (threshold_image [0 :h , 0 :cell_width ])
39
+ cells [1 ] = cv2 .countNonZero (threshold_image [0 :h , cell_width :cell_width * 2 ])
40
+ cells [2 ] = cv2 .countNonZero (threshold_image [0 :h , cell_width * 2 :cell_width * 3 ])
41
+ cells [3 ] = cv2 .countNonZero (threshold_image [0 :h , cell_width * 3 :cell_width * 4 ])
42
+ cells [4 ] = cv2 .countNonZero (threshold_image [0 :h , cell_width * 4 :cell_width * 5 ])
43
+ cells [5 ] = cv2 .countNonZero (threshold_image [0 :h , cell_width * 5 :cell_width * 6 ])
44
+ cells [6 ] = cv2 .countNonZero (threshold_image [0 :h , cell_width * 6 :w ])
45
+
46
+ # obtaining the most active range
47
+ to_press = np .argmax (cells )
48
+
49
+ # return the most active cell, if threshold met
50
+ if (cells [to_press ] >= self .THRESHOLD ):
51
+ return to_press
52
+ else :
53
+ return None
0 commit comments