[Python Study Notes]行人檢測

# --------------------------------------------------------------
# @文件: 行人識別.py
# @工程: blog
# @時間: 2018/3/16 21:12
# @做者: liu yang
# @博客: liuyang1.club
# @郵箱: liuyang0001@outlook.com
# -------------------------------------------------------------
# 編碼格式
# -*- coding: utf-8 -*-
# Python版本
# #!/usr/bin/python3

import cv2


def draw_detection(img, rects):
    for x, y, w, h in rects:
        pad_w, pad_h = int(0.05 * w), int(0.05 * h)
        cv2.rectangle(img, (x + pad_w, y + pad_h), (x + w - pad_w, y + h - pad_h), (0, 255, 0), 2)


def draw_alart(img, rects):
    area = [0, 2]
    size = img.shape
    area_img = size[0] * size[1]
    for x, y, w, h in rects:
        area.append(w * h)
    thresh = 0.25
    if max(area) / area_img > thresh:
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, "Incoming Peaple", (round(size[0] / 2) - 80, round(size[1] / 2) - 50),
                    font, 6, (0, 0, 255), 25)


# 傳入opencv裏默認的參數
hog = cv2.HOGDescriptor()
# 獲得行人的特徵值
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# 調用攝像頭,也能夠傳入一個路徑視頻文件
cap = cv2.VideoCapture(0)
while True:
    # ret是一個表
    # 循環讀取每一幀的數據
    ret, frame = cap.read()
    # 掃描圖像,若是檢測不到進行縮小檢測
    found, w = hog.detectMultiScale(frame, 0, winStride=(8, 8), padding=(8, 8), scale=1.05)
    draw_detection(frame, found)
    draw_alart(frame, found)
    # 顯示每一幀的畫面
    cv2.imshow("pd", frame)
    # 按q退出
    key = cv2.waitKey(1) & 0xff
    if key == ord('q'):
        break

# 運行結束後釋放攝像頭
cap.release()
cv2.destroyAllWindows()
相關文章
相關標籤/搜索