The inter-frame difference method is one of the methods for detecting moving objects. It is the result made with Python3 + OpenCV.
Click here for the original data (It's hard to understand, but it's a video that feels like splashing water on the beach)
** Click here for the binarized mask image **
** This is a video **
** Display background image **
Then it is a sample program.
movieSample.py
import cv2
import numpy as np
import time
i = 0 #Count variable
th = 30 #Difference image threshold
#Video file capture
cap = cv2.VideoCapture("/Users/.../.../.../movies/movieSample.mp4")
#Set the first frame as the background image
ret, bg = cap.read()
#Grayscale conversion
bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
while(cap.isOpened()):
#Get frame
ret, frame = cap.read()
#Grayscale conversion
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#Calculate the absolute value of the difference
mask = cv2.absdiff(gray, bg)
#Binarize the difference image and mask image(Monochrome)Calculate
mask[mask < th] = 0
mask[mask >= th] = 255
#Display mask image
cv2.imshow("Mask", mask)
#Display frame image (monochrome)
cv2.imshow("Flame", gray)
#Display background image (monochrome)
cv2.imshow("Background", bg)
#Wait(0.03sec)
time.sleep(0.03)
i += 1 #Increase the count by 1
#Background image update (at regular intervals)
if(i > 30):
ret, bg = cap.read()
bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
i = 0 #Initialization of count variable
#Stops halfway when the x key is pressed
if cv2.waitKey(1) & 0xFF == ord('x'):
break
cap.release()
cv2.destroyAllWindows()
You may need to install OpenCV separately as a trial. Please try according to the environment. If you are using a Mac, from the terminal
$ python3 -m pip install opencv-python [ENTER]
I think I can go there.
** K Igarashi ** has introduced the installation. Install OpenCV with pip
Recommended Posts