Motion detection opencv python

Detecting Motion with OpenCV — Image Analysis for Beginners

How to detect and analyze moving objects with OpenCV

Motion detection has many purposes. You can use it to start recording once you see movement on a wildlife camera or a security camera, e.g. Another application is performance-improvement. Instead of analyzing a whole image, we only have to work with small parts that moved. Like only identifying the color of the moving cars in the image above.

In this article, we’ll create a fully working motion detector that can be used for all of the use-cases above. In the process, we’ll learn a lot about processing images with OpenCV. At the end of this article, you’ll have a fully operational motion detector and a lot more knowledge about image processing. Let’s code!

Series

This article is part of a series about OpenCV image processing. Check out the other articles:

  • Reading images, video’s, your screen and the webcam
  • Detecting and blurring faces
  • Destroying Duck Hunt with template matching: finding images in images
  • Creating a motion-detector (📍 You are here!)
  • Detecting shapes without AI (under construction; coming soon)
  • Detecting and reading text from images (under construction; coming soon)
Читайте также:  List subtract list python

Setup

Our client asked us to create some software for analyzing transportation in a city. They want to know how many bikes, cars, buses and pedestrians visit a particular location on a given day. We’ve installed a webcam that films the locations.

The data-science team has some very fancy models for determining whether a particular image is a bike, bus, car of person but they cannot run this model on the entire image. It is our task to pre-process the image. We need to take small snippets that we can run the identification model on.

How do we actually detect movement? We are going to compare each frame of a video stream from my webcam to the previous one and detect all spots that have changed. The end result will look something like this:

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Detects Motion in the Real Time

License

jitendrasb24/Motion-Detection-OpenCV

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Motion Detection technology in Commonly used in our daily life. This feature is used in CCTV Cameras to detect any kind of motion in the video frame. In this repository, we are going to make a motion detection script using OpenCV in Python.

First of all make sure you have Python installed in your system.

Secondly you have to install pip. It can be installed easily using command prompt.

The last requirement is the OpenCV module. It can be installed using pip.

STEPS FOR MOTION DETECTION USING OPENCV AND PYTHON

STEP 1:- Capturing Real-time video from a camera or Reading recorded video.

STEP 2:- Read two frames from the video source.

STEP 3:- Find Out the Difference between the next frame and the previous frame.

STEP 4:- Apply Image manipulations like Blurring, Thresholding, finding out contours, etc.

STEP 5:- Finding Area of Contours to detect Motion.

STEP 6:- Drawing Rectangle on the Motion Detected Areas.

STEP 7:- Showing the video in the window.

We use this command in openCV to Capture Video, in which you have to detect movement.

cv2.VideoCapture(0) ---- Captures video from your webcam. cv2.VideoCapture("video path") ---- It uses the video stored in the given path. cv2.VideoCapture(1) ---- Captures video from external Camera i.e: Usb camera. 

In Order to Detect motion in a frame we also need to have the previous frame with us, so we can say there is any kind of movement in the next frame or not.

ret, frame1 = cap.read() ret, frame2 = cap.read() 

FINDING THE DIFFERENCE BETWEEN THE FRAMES

absdiff() function is used to find the absolute difference between frame1 and frame2. As the Difference can’t be negative in this case, so absolute difference is taken.

diff = cv2.absdiff(frame1, frame2) 

The difference between the two frames is stored in diff variable and the next process will be held on the difference frame.

Now it is time for image manipulation techniques on the different frames.

First of all the “difference” frame is converted from coloured to grayscale image using cvtColor() function in OpenCV.

diff_gray = cv2.cvtColor(diff, cv.COLOR_BGR2GRAY) 

The diff_gray grayscaled image is then blurred using Gaussian Blur, using a 5×5 Kernel.

The blurring method removes noise from an image and thus good for edge detection.

blur = cv2.GaussianBlur(diff_gray, (5, 5), 0) 

The Blurred image is then thresholded using the cv.THRESH_BINARY. Basically the image now contains either 255 or 0 in the matrix.

This threshold function takes a grayscale image and also takes the min and max threshold values.

cv.THRESH_BINARY – returns 0 if the color value of that pixel is below the min threshold value, and returns max threshold value if the pixel is greater than the min threshold value. And thus the image contains only low or high value.

_, thresh = cv2.threshold(blur, 20, 255, cv.THRESH_BINARY) 

The thresholded image is then dilated. Dilation means Adding pixels to the boundaries of objects in an image. The total number of iterations is 3 in this case, which means the same function will be repeated 3 continuous times.

dilated = cv2.dilate(thresh, None, iterations=3) 

The dilated image is then used for finding out contours.

findCotours() use cv.RETR_TREE and cv.CHAIN_APPROX_SIMPLE technique for finding out contours in the dilated image.

findContours() returns a list of contours.

contours, _ = cv2.findContours( dilated, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) 

contours variable is a list of all the contours that were found using findContours() function.

for contour in contours: (x, y, w, h) = cv2.boundingRect(contour) if cv2.contourArea(contour) < 900: continue cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.putText(frame1, "STATUS: <>".format('MOTION DETECTED'), (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (217, 10, 10), 2) 

boundingRect() function returns the coordinates and width and height of the bounding rectangle.

cv.contourArea(contour) takes contour as an argument and returns the area bound by the contour.

If the area of the contour is above 900 in this case. Then a rectangle is drawn covering that object, showing that the object moved when compared to the last frame, and the area covered by the motion was above 900.

Text is also put on the video frame “STATUS: MOTION DETECTED” when there is motion detected in the video frame.

JITENDRA SINGH BISHT

Источник

Распознавание движения в Python OpenCV

В одной из прошлых статей по OpenCV мы узнали как выводить контуры изображения из видео потока и нормализовать их т.е. избавиться от лишних контуров. В этой статье мы познакомимся с концепцией вычитания кадров, т.е. нахождение разницы между двумя кадрами видео потока, а также познакомимся с некоторыми новыми методами библиотеки Opencv: absdiff(), threshold(), dilate(), findContours(), boundingRect(), contourArea().

Запустив данный скрипт, вы увидите как он распознает движение на видеопотоке, окружая движущийся объект зеленым контуром.

import cv2 # импорт модуля cv2

#cv2.VideoCapture(«видеофайл.mp4»); вывод кадров из видео файла
cap = cv2.VideoCapture(0); # видео поток с веб камеры

cap.set(3,1280) # установка размера окна
cap.set(4,700)

ret, frame1 = cap.read()
ret, frame2 = cap.read()

while cap.isOpened(): # метод isOpened() выводит статус видеопотока

diff = cv2.absdiff(frame1, frame2) # нахождение разницы двух кадров, которая проявляется лишь при изменении одного из них, т.е. с этого момента наша программа реагирует на любое движение.

gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # перевод кадров в черно-белую градацию

blur = cv2.GaussianBlur(gray, (5, 5), 0) # фильтрация лишних контуров

_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) # метод для выделения кромки объекта белым цветом

dilated = cv2.dilate(thresh, None, iterations = 3) # данный метод противоположен методу erosion(), т.е. эрозии объекта, и расширяет выделенную на предыдущем этапе область

сontours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # нахождение массива контурных точек

for contour in сontours:
(x, y, w, h) = cv2.boundingRect(contour) # преобразование массива из предыдущего этапа в кортеж из четырех координат

# метод contourArea() по заданным contour точкам, здесь кортежу, вычисляет площадь зафиксированного объекта в каждый момент времени, это можно проверить
print(cv2.contourArea(contour))

if cv2.contourArea(contour) < 700: # условие при котором площадь выделенного объекта меньше 700 px
continue
cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2) # получение прямоугольника из точек кортежа
cv2.putText(frame1, «Status: <>«.format(«Dvigenie»), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3, cv2.LINE_AA) # вставляем текст

#cv2.drawContours(frame1, сontours, -1, (0, 255, 0), 2) также можно было просто нарисовать контур объекта

cv2.imshow(«frame1», frame1)
frame1 = frame2 #
ret, frame2 = cap.read() #

if cv2.waitKey(40) == 27:
break

Создано 16.04.2020 13:45:30

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Оцените статью