OPENCV- MOVING OBJECT DETECTION

Powerful learning
2 min readJan 6, 2023

--

I am a Youtuber. My channel name is Powerful Learning. I post free certifications, free internships and free webinars.

I have already posted opencv beginner level tutorials and code on medium and Youtube. Kindly take a look

  1. openv — read,write and show an image -link
  2. opencv — color image to grayscale image -link
  3. opencv- to print image property — link
  4. opencv — Resize an image-link
  5. opencv — normal image to blurred image -link
  6. opencv- videostreaming (turn on webam) — link

code

KINDLY SEE VIDEO TO KNOW INDENTATION AND COMMENT LINES.MEDIUM IS NOT SUPPORTING TO LEAVE SPACES-link

import imutils
‘’’to make basic image processing functions
such as translation, rotation, resizing,etc’’’
import cv2
import time
cam=cv2.VideoCapture(0)
‘’’try giving 1 or 2 if 0 is not working’’’

time.sleep(1)
firstScreen=None
‘’’to capture first frame(normal frame)’’’
area=500

while True: #infinite loop
flag,image=cam.read()
‘’’VideoCapture returns a tuple (return value, image)’’’
text=”Normal”
image=imutils.resize(image,width=500)

‘’’adjusting the frame (crop)’’’
grayImage=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)#color2Gray sca
‘’’color image to grayscale — to know more
tutorial link in description’’’
gaussianImage=cv2.GaussianBlur(grayImage,(21,21),0)#smoothened
‘’’ to smoothen the image / to blurr — to know more
link in description’’’

if firstScreen is None: #initially assigned to None
firstScreen=gaussianImage
#capturing first frame on 1st iteration
continue

imageDiff=cv2.absdiff(firstScreen,gaussianImage)#absolute diffb/w
‘’’finding the absolute difference between the pixels of
the two image arrays. By using this we will be able
to extract just the pixels of the objects that are moving.’’’

threshImage=cv2.threshold(imageDiff,25,255,cv2.THRESH_BINARY)[1]
#Thresholding is the binarization of an image: max- white

threshImage=cv2.dilate(threshImage,None,iterations=2)
‘’’It increases the size of the objects.
It fills the holes and broken areas.
the line joining all the points along the boundary
of an image that are having the same intensity.’’’

cnts=cv2.findContours(threshImage.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
‘’’cv2. CHAIN_APPROX_SIMPLE returns only the endpoints
cv2.RETR_EXTERNAL — retrieves only the extreme outer contours’’’
cnts=imutils.grab_contours(cnts)

for c in cnts:
if cv2.contourArea(c)<area:
continue
(x,y,w,h)=cv2.boundingRect(c)
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
text=”Moving Object detected”
print(text)

cv2.putText(image,text,(10,20), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2)
‘’’cv2.putText(image, text, org, font,
fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])’’’
cv2.imshow(“cameraFeed”,image)
key=cv2.waitKey(1) & 0xFF
if key == ord(“q”):
break
cam.release()
cv2.destroyAllWindows()

--

--

Powerful learning

Mini blog on Free certifications, internships and webinars