Created
December 12, 2017 08:50
-
-
Save six519/3d1717ebc646cf207e8e63cfdf3e26f3 to your computer and use it in GitHub Desktop.
(Ruby Sample Code) Basic Motion Detection With OpenCV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'opencv' | |
include OpenCV | |
camera = CvCapture.open #open camera | |
#set the video size to 512x288 | |
camera.width = 512 | |
camera.height = 288 | |
window = GUI::Window.new 'Camera' | |
sleep 3 | |
#convert to grayscale | |
firstFrame = camera.query.BGR2GRAY | |
firstFrame = firstFrame.smooth CV_GAUSSIAN, 21, 21, 0 | |
while not GUI::wait_key 1 | |
frame = camera.query | |
gray = frame.BGR2GRAY | |
gray = gray.smooth CV_GAUSSIAN, 21, 21, 0 | |
frameDelta = firstFrame.abs_diff gray | |
thresh = frameDelta.threshold 25, 255, CV_THRESH_BINARY | |
thresh = thresh.dilate nil, 2 | |
cnts = thresh.find_contours(:mode => CV_RETR_EXTERNAL, :method => CV_CHAIN_APPROX_SIMPLE) | |
while cnts | |
if cnts.contour_area < 500 | |
cnts = cnts.h_next | |
next | |
end | |
frame.put_text!("Motion Detected", CvPoint.new(10, 20), CvFont.new(:simplex), CvColor::Red) | |
cnts = cnts.h_next | |
end | |
window.show frame | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment