OpenCV|to find people who is moving
OpenCV| to find people who is moving
Hello, everyone. Today, I will show you how to use your computer to capture people moving in your camera based on OpenCV in your python. Let’s start right now!
1.Import your module, cv2 and numpy.
import cv2
import numpy as np
2.Open your camera on your computer and save pictures in frames.
cap = cv2.VideoCapture(0)
ret, frame1 = cap.read()
ret, frame2 = cap.read()
Remember: There are two frames captured from camera because we will compare the difference between them to find characteristics.
3.Deal with frames and find the moving things.
while cap.isOpened():
diff = cv2.absdiff(frame1,frame2) # to capture the difference of these two frames. Calculates absolute difference.
gray = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY) # to make your picture gray
blur = cv2.GaussianBlur(gray,(5,5),0) # use gaussianblur to make your picture smoother
_,thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # to set up the threshold.If the number of color is beyond 20, it will become white(255), while by contrast, it will beacome black(0).
dilated = cv2.dilate(thresh,None,iterations=3) # to make the point bigger than ever before
contours,_ = cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # to find the edge
The figure shows the result of dilating. I just move my head in front of camera, and it capture my head!
4.Draw the rectangle based on the edge of the picture.
for contour in contours:
(x,y,w,h) = cv2.boundingRect(contour) # it will return the x and y on the left-up point and w,h is the width and height of the picture
if cv2.contourArea(contour) < 1000: # your contours include the Squareof area.if it is not bigger than 1000, ignore it
continue
cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) #draw the rectangle
cv2.putText(frame1,'Status: movement',(10,20),cv2.FONT_HERSHEY_SIMPLEX,
1,(0,0,255),3) #if you move, it will show "movement"
5. show your video and do the loop to continue your program.
cv2.imshow("inter",frame1)
cv2.imshow("contour",dilated) #just in order to compare the difference between "dilated" and frame
frame1 = frame2 # this step is necessary. you have to contiune the comparison based on this step.
ret,frame2 = cap.read()
6. touch “Esc” to quit the program and release your computer.
if cv2.waitKey(40) ==27: # "27" is the number of "Esc"
break
cv2.destroyAllWindows()
cap.release()
In conclusion, there are several important steps to deal with your picture: adsdiff, gaussianblur, dilate and findcontours. It’s so easy to draw the rectangle., and you should pay more attention to the step 5, which is the core of loop.
That’s all, thank you for watching.