【Python】Opencv检测行人

# coding:utf-8

import cv2
from timeit import default_timer as timer


class Predict(object):
    def __init__(self):
        # 获取hog检测器对象
        self.hog = cv2.HOGDescriptor()
        # 设置检测人的默认检测器
        self.hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
        print("模型加载完成!")

    # 检测i方框 包含o方框
    def is_inside(self, o, i):
        ox, oy, ow, oh = o
        ix, iy, iw, ih = i
        return ox > ix and ox + ow < ix + iw and oy + oh < iy + ih

    # 将人外面的方框画出来
    def draw_person(self, image, person):
        x, y, w, h = person
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 255), 2)

    def detect_img(self, img):
        # 在图片中检测人,
        # 返回found列表 每个元素是一个(x, y, w, h)的矩形,w是每一个矩形的置信度
        found, w = self.hog.detectMultiScale(img)
        found_filtered = []
        # 如果方框有包含,只留下内部的小方块
        for ri, r in enumerate(found):
            for qi, q in enumerate(found):
                if ri != qi and self.is_inside(r, q):
                    break
                else:
                    found_filtered.append(r)

        # 将每一个方块画出来
        for person in found_filtered:
            self.draw_person(img, person)

        return img

    def detect_video(self, video_path):
        vid = cv2.VideoCapture(video_path)
        if not vid.isOpened():
            raise IOError("Couldn't open webcam or video")

        while True:
            return_value, frame = vid.read()
            t1 = timer()
            result = self.detect_img(frame)
            t2 = timer()
            fps = 1 / (t2 - t1)
            print(fps)
            cv2.imshow("person detection", result)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break


if __name__ == '__main__':
    predict = Predict()
    # 检测图片
    if False:
        img = cv2.imread("person1.jpg")
        result = predict.detect_img(img)
        cv2.imshow("person detection", result)
        cv2.waitKey()
        cv2.destroyAllWindows()

    # 检测视频
    if True:
        video_path = 'video1.mp4'
        predict.detect_video(video_path=video_path)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天边星宿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值