基于差值的运动物体检测

 

'''
区域目标运动检测
关键字:
    cv2: 摄像头视频读取,运动物体框跟踪, 基于与初始背景图的差别得到二值图
    os:window控制,执行exe
    configparser:配置文件写入读取
优点:
    占用资源极小,调整检测窗口至需要检测的位置,当有物体运动则自动触发设定好的exe(如浏览器),防背后有人居家必备√
'''
# coding=utf-8

import cv2
import os
import time
import numpy as np
import configparser


# config set
path = os.getcwd()
conf = configparser.ConfigParser()

# read and save config
while True:
    is_read = conf.read(filenames=path + r'\config_motion_detector')
    if is_read == []:
        # add section
        gadget_open_default = 'C:\Program Files\internet explorer\iexplore.exe'
        conf.add_section('detect_frame')
        conf.add_section('contours')
        conf.add_section('gadget_path')
        conf.add_section('binaryzation')
        conf.add_section('set')
        # set detect frame
        conf.set('detect_frame', 'detect_frame_vertical_1', '80')
        conf.set('detect_frame', 'detect_frame_vertical_2', '180')
        conf.set('detect_frame', 'detect_frame_horizon_1', '0')
        conf.set('detect_frame', 'detect_frame_horizon_2', '200')
        # for contours threshold
        conf.set('contours', 'contours_threshold', '1000')  # the size of contours covering motion object
        # for gadget path
        conf.set('gadget_path', 'gadget_path', gadget_open_default)
        conf.set('binaryzation', 'binaryzation_threshold', '8')
        conf.set('set','is_show_video','1')
        conf.write(open(path + r'\config_motion_detector', 'w+'))
        print("initialized config file")
    else:
        try:
            detect_frame_vertical_1 = int(conf.get('detect_frame','detect_frame_vertical_1'))
            detect_frame_vertical_2 = int(conf.get('detect_frame','detect_frame_vertical_2'))
            detect_frame_horizon_1 = int(conf.get('detect_frame','detect_frame_horizon_1'))
            detect_frame_horizon_2 = int(conf.get('detect_frame','detect_frame_horizon_2'))
            contours_threshold = int(conf.get('contours','contours_threshold'))
            binaryzation_threshold = int(conf.get('binaryzation','binaryzation_threshold'))
            is_show_video = int(conf.get('set','is_show_video'))
            gadget_open_default = conf.get('gadget_path','gadget_path')
            print("loaded config file")
            break
        except:
            pass

# gadget need opening
gadget_open = gadget_open_default

# capture video from camera
camera = cv2.VideoCapture(0) # 0:the first camera
time.sleep(0.5)
print("is camera opened:",camera.isOpened())

capture_size = (camera.get(cv2.CAP_PROP_FRAME_WIDTH),camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
print("camera size:",capture_size)

#  for inflation
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(9,4))

background = None
calc_n = 0
is_open_gadget = 0
time_start = time.time()
time_flag = time_start
while True:
    # read video (every frame)
    grabbed,frame_lwpCV = camera.read()
    frame_lwpCV = frame_lwpCV[detect_frame_vertical_1:detect_frame_vertical_2,detect_frame_horizon_1:detect_frame_horizon_2]
    # preprocess, to gray ,gauss filter(gauss blur:reduce noise)
    gray_lwpCV = cv2.cvtColor(frame_lwpCV,cv2.COLOR_RGB2GRAY)
    gray_lwpCV = cv2.GaussianBlur(gray_lwpCV,(21,21),0)

    # first frame as background
    if background is None:
        background = gray_lwpCV
        continue

    # calculate differ between each frame and background,got a different map
    different_map_1 = cv2.absdiff(background,gray_lwpCV)
    # binaryzation
    different_map_2 = cv2.threshold(different_map_1,binaryzation_threshold,255,cv2.THRESH_BINARY)[1]
    # inflation
    #different_map_2 = cv2.dilate(different_map_2,es,iterations=2)

    if np.max(different_map_2) != 0:
        calc_n += 1
        print("warring! ! ! x",calc_n )
    if np.max(different_map_2) != 0 and is_open_gadget == 0:
        try:
            os.startfile(gadget_open)
        except:
            print("warring:wrong open path")
        is_open_gadget = 1

    # calculation contours
    # find contours !
    image,contours,hierarchy = cv2.findContours(different_map_2.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    for c in contours:
        if cv2.contourArea(c) < contours_threshold:
            # only show contours over threshold(reduce noise influence)
            continue
        # calculation rectangle boundary frame(show the green rectangle cover object[moving])
        (x,y,w,h) = cv2.boundingRect(c)
        cv2.rectangle(frame_lwpCV,(x,y),(x+w,y+h),(0,255,0),2)

    # show
    if is_show_video == 1:
        cv2.imshow('contours:',frame_lwpCV)
        cv2.imshow('dis:',different_map_2) # show different map

    # exit judge
    if cv2.waitKey(1) == ord('q'):
        break

    # reset background , is_open_gadget
    if int(time.time() - time_start) % 5 == 0:
        background = gray_lwpCV

    if int(time.time() - time_start) % 10 == 0 and int(time.time()) - int(time_flag) > 1:
        is_open_gadget = 0
        time_flag = int(time.time())
    time.sleep(0.05)

camera.release()
cv2.destroyAllWindows()

'''

.配置文件中的gadget_path后的值,可以更改为任意软件或文件夹的地址,检测到物体运动时会自动打开
.配置文件中的[detect_frame]为检测框位置,依次为 长(上,下),宽(左,右)
.配置文件中的[binaryzation]为二值化阈值,数值越低,在光线阴暗的地方可以提高识别率,同时也会增加误判率
.配置文件中的[set]  1 = 显示实时计算画面,0 = 隐藏实时计算画面
.配置文件中的[contours]为标记框阈值,若物体大小小于该值则不会框中
.请勿删除配置文件的值(可更改,不可删除)
.若发生bug,请删掉配置文件再重新执行exe,将会重新生成配置文件
.为防止疯狂打开设定的软件,该程序设定为10秒钟内只会打开一次设定的软件

 

'''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: OpenCvSharp是一个基于开源计算机视觉库OpenCV的C#封装。在OpenCvSharp中,我们可以使用各种算法和功能来实现运动物体检测运动物体检测是一种在连续帧图像中检测并跟踪运动物体的技术。在OpenCvSharp中,我们可以使用帧差法或光流法等方法来实现运动物体检测。 帧差法是一种基于像素级别的比较帧之间差异的方法。通过计算当前帧和前一帧之间的差异,我们可以检测到图像中的运动物体。在OpenCvSharp中,我们可以使用absdiff函数来计算差异图像,并使用阈值化来提取感兴趣的运动物体。 光流法是一种基于像素的运动估计方法。它通过计算每个像素在连续帧之间的位移量来检测运动物体。在OpenCvSharp中,我们可以使用calcOpticalFlowPyrLK函数来计算光流,并通过阈值化来提取运动物体。 除了帧差法和光流法,OpenCvSharp还提供了其他一些功能和算法来实现运动物体检测。例如,我们可以使用背景减除方法来提取前景运动物体,或者使用卡尔曼滤波器来预测运动物体的位置。 总的来说,OpenCvSharp是一个强大的工具,可以帮助我们实现运动物体检测。通过使用OpenCvSharp中的各种功能和算法,我们可以有效地检测和跟踪运动物体,在许多实际应用中具有广泛的用途。 ### 回答2: 运动物体检测是指利用计算机视觉技术来识别和跟踪视频中的运动物体。OpenCVSharp是一个基于OpenCV的跨平台计算机视觉库,通过使用OpenCVSharp库,我们可以很方便地实现运动物体检测。 通过OpenCVSharp库,我们可以先对输入的视频进行前景和背景的分割,将运动物体和静止背景进行区分。这样做的目的是为了减少噪音和其他不相关的运动。 接下来,我们可以使用运动物体检测算法,例如光流算法或帧差算法,来检测视频中的运动物体。光流算法可以估计图像中每个像素的运动方向和速度,从而确定运动物体的位置和形状。帧差算法则是通过比较相邻帧之间的像素差异,来确定哪些像素发生了运动。 在检测运动物体后,我们可以用矩形框或其他形状将其标记出来,并可以进行进一步的处理,例如追踪运动物体的轨迹或计算其运动速度等。 值得注意的是,运动物体检测是一个复杂的问题,受到许多因素的影响,例如背景干扰、光照条件和摄像机的运动等。因此,为了获得更好的检测结果,我们可能需要进行参数调优和算法组合。 总结而言,OpenCVSharp可以帮助我们实现运动物体检测,为我们提供了许多工具和算法来处理视频中的运动物体。通过合理地选择算法和优化参数,我们可以在视频中准确地检测和跟踪运动物体,从而满足各种应用场景的需求。 ### 回答3: OpenCvSharp 是一个基于C#的开源计算机视觉库,其中包括了丰富的图像处理和计算机视觉算法。运动物体检测是其中的一个重要应用之一。 在 OpenCvSharp 中,可以利用背景差分法来实现运动物体检测。背景差分法是一种简单且常用的方法,它通过对当前帧与背景图像进行像素级别的比较,来寻找出像素值变动较大的区域,从而检测运动物体。 首先,需要获取一个背景图像作为比较基准。可以通过采集一段静止的背景或者使用平均值法得到。然后,对于每一帧图像,可以使用差分运算求得每个像素点与背景图像之间的差值。通过设定一个阈值,将差值大于阈值的像素点标记为前景,即表示对应像素位置存在运动物体。 为了进一步优化运动物体检测的结果,可以对前景区域进行形态学操作,如膨胀和腐蚀等,以去除噪声或者连接分散的前景区域。此外还可以利用背景建模和光流等方法进行改进。 在OpenCvSharp中,提供了各种相关的函数和方法,如BackgroundSubtractor类和相应的算法实现,包括KNN、MOG和MOG2等。通过调用这些函数和方法,结合合适的参数设置,即可实现准确和可靠的运动物体检测。 总之,OpenCvSharp提供了丰富的工具和算法来实现运动物体检测。我们可以利用背景差分法,结合形态学操作和其他优化方法,将其应用于视频监控、智能交通系统等领域,实现对运动物体的实时检测和跟踪。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值