差分法:实现运动检测:

一.原理: 利用两图像相减,从而检测出物体

二.实现:

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()

                
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值