How to Detect An Object With OpenCV (Python)
OpenCV is the massive open source
library for computer vision, machine learning, and image processing. Now it plays an important role in real time operations which is very important in the current system. By using
, images and video identification objects can be processed. faces or even the handwriting of a human. This article focuses on object detection.
Source code:
import cv2
video_object = cv2.VideoCapture(0)
while True:
check, live_frame =video_object.read()
is_motion_detected = 0
gray = cv2.cvtColor(live_frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21,21),0)
if intial_static_video_frame is None:
intial_static_video_frame = gray
continue
difference_frame = cv2.absdiff(intial_static_video_frame, gray)
threshold_frame = cv2.threshold(difference_frame, 30,255, cv2.THRESH_BINARY)[1]
threshold_frame =cv2.dilate(threshold_frame, None, iterations = 2)
cnts, hierarchy =cv2.findContours(threshold_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in cnts:
if cv2.contourArea(contour):
continue
is_motion_detected = 1
(x,y,w,h) = cv2.boundingRect(contour)
cv2.rectangle(live_frame, (x,y), (x + w, y + h), (0, 255, 255), 3)
cv2.imshow("Gray frame", gray)
cv2.imshow("Difference frame", difference_frame)
cv2.imshow("Threshold frame", threshold_frame)
cv2.imshow("Color frame", live_frame)
key =cv2.waitKey(1)
if key == ord('q'):
break
video_object.release()
cv2.destroyAllWindows()

If you have any doubts.please let me know