Introduction and goal
I have always wanted a software based on the webcam that can detect movement and record in a video file only something is moving. It is now done. :) Indeed it is not really conceivable to record all along because the hard disk drive would be quickly filled if the software has to run a day for instance. Because I love OpenCV and du to lack of this kind of software on Linux I have decided to do it. As said before the program analyse the images taken from the webcam and intent to detect movement. If a movement is detected the program start recording the webcam in a video file fo 10 seconds. After that if a movement is again detected it still record until movements stops.
This project is hosted on my Github.
The trivial way
I have implement two different algorithms to detect movement the first is the most trivial in his way to behave. The trivial idea is to compute the difference between two frames apply a threshold the separate pixels that have changed from the others and then count all the black pixels. Then the average is calculated with this count and the total number of pixels and depending of the ceil the event is triggered or not.
The code:
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 |
|
Additional informations:
- initRecorder: initialise the recorder with an arbitrary codec it can be changed with problems
- in the run method no motion can be detected in the first 5 second because it is almost the time needed for the webcam to adjust the focus and the luminosity which imply lot’s of changes on the image
- processImage: contains all the images operations applied to the image
- somethingHasMoved: The image iteration to count black pixels is contained in this method
The result:
The smart way
I call it the smart way, because his way to operate is less trivial than the previous one, but the results are identical if not more accurate in the previous method. I inspired myself of the Motion-tracker by Matt Williamson for the operations and filters to apply on the image but all the rest is different. The idea in this method is to find the contours of the moving objects and calculate the area of all of them. Then the average of the surface changing is compared with the total surface of the image and the alarm is triggered if it exceed the given threshold. Note the code shown below does not implement the recording system as it is the case on the previous example, but it can be made easily.
The code:
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 |
|