一.原理: 利用两图像相减,从而检测出物体
二.实现:
1.差分法:
diff = cv2.absdiff(gray_frame, background) #两图像相减 ret, diff = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY) # 高于50px,设为白色,低于50px,设为黑色,返回:ret:是否成功,diff: 图像 diff = cv2.dilate(diff, es, 3) #进行膨胀
2.contours, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 为了更好地实现finContours,因此需要先将图片转化为二值图像,
黑色为背景,白色为物体,因为findContours 会改变原图像,为了防止修改原图像,故需copy
3.画框: (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2
import datetime
import cv2
background = None
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 4))
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_frame = cv2.GaussianBlur(gray_frame, (25, 25), 3)
if background is None:
background = gray_frame
continue
diff = cv2.absdiff(gray_frame, background)
ret, diff = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY)
diff = cv2.dilate(diff, es, 3)
contours, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
is_detected = False
for c in contours:
if cv2.contourArea(c) < 2000:
continue
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
is_detected = True
if is_detected:
show_text = "Motion: Detected"
show_color = (0, 0, 255)
else:
show_text = "Motion: Undetected"
show_color = (0, 255, 0)
cv2.putText(frame, show_text, (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, show_color, 2)
cv2.putText(frame,
datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
(10, frame.shape[0] - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.35, show_color, 2)
cv2.imshow("vedio", frame)
cv2.imshow("diff", diff)
key = cv2.waitKey(1) & 0xFFF
if key == ord("q"):
break
camera.release()
cv2.destroyAllWindows()