opencv实现运动物体检测跟踪

本文介绍了一种使用OpenCV库进行运动物体跟踪的方法。通过创建背景减除器并应用阈值和形态学操作来检测和跟踪视频中的运动物体。此方法在实时视频流中实现了有效的物体检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

利用opencv实现运动物体的跟踪

# video传入一个视频路径
def detect_video(video):
    camera = cv2.VideoCapture(video)
    history = 1

    bs = cv2.createBackgroundSubtractorKNN(detectShadows=True)
    bs.setHistory(history)

    frames = 0

    while True:
        res, frame = camera.read()

        if not res:
            break

        fg_mask = bs.apply(frame)  

        if frames < history:
            frames += 1
            continue

        th = cv2.threshold(fg_mask.copy(), 244, 255, cv2.THRESH_BINARY)[1]
        th = cv2.erode(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2)
        dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 3)), iterations=2)

        image, contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for c in contours:
            # 获取矩形框边界坐标
            x, y, w, h = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        cv2.imshow("track", frame)
        cv2.imshow("process", dilated)
        if cv2.waitKey(110) & 0xff == 27:
            break
    camera.release()

                                                                      
最后欢迎大家扫描关注公众号获取源码与交流。
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值