1. 程式人生 > >[Python Study Notes]物體運動檢測

[Python Study Notes]物體運動檢測

copy button waitkey oca lag 圖像轉換 pri bsdiff 模塊

基於opencv的cv2模塊實現

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘
>>文件: iot_client.py
>>作者: liu yang
>>郵箱: [email protected]
>>博客: www.cnblogs.com/liu66blog
>>博客: liuyang1.club (抱歉,域名備案中,稍後恢復訪問)

‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘‘

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2
import numpy as np
import easygui
import datetime
from twilio.rest import Client

# 打開攝像頭
camera= cv2.VideoCapture(0)
# 如果攝像頭打開失敗
if camera.isOpened() == False:
    # 給與友好性提示
    easygui.msgbox("\n\n\n\n\n\n                 請保證攝像頭可以正常被打開,請檢查硬件後重新運行",title=‘提示框‘,ok_button=‘確定‘)
# 得到攝像頭的圖像尺寸
size = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
# 打印尺寸
print(‘size:‘+repr(size))
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,4))
kernel = np.ones((5,5),np.uint8)
background = None
flag = 0
while True:
    # 有沒有檢測到的文本
    text = "Undetected"
    # 讀取攝像頭的參數
    grabbed , frame_lwpCV=camera.read()
    try:
        # 將圖像轉換為RGB
        gray_lwpCV = cv2.cvtColor(frame_lwpCV,cv2.COLOR_RGB2GRAY)
        # 將圖像進行高斯濾波,去除噪點
        gray_lwpCV = cv2.GaussianBlur(gray_lwpCV,(25,25),3)
    except cv2.error:
        break

    # 判斷是否有標準的背景圖,如果沒有就將上面攝像頭采集的第一幀的圖像作為背景圖
    if background is None:
        background = gray_lwpCV
        continue
    # 將兩個圖像進行比較
    diff = cv2.absdiff(background,gray_lwpCV)
    diff = cv2.threshold(diff,50,255,cv2.THRESH_BINARY)[1]
    # 進行3次膨脹
    diff = cv2.dilate(diff,es,iterations=3)

    # 忽略掉一些很小的因素
    image , contours , hierarchy = cv2.findContours(diff.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    for c in contours:
        # 如果變化的狂過小,則忽略
        if cv2.contourArea(c) < 2000:
            continue
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame_lwpCV, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 有物體闖入到背景中,以文本標記
        text = "Detected"

    # 如果文本標記為無
    if text == "Undetected" :
        # 在圖像上標出
        cv2.putText(frame_lwpCV,"Motion: {}".format(text),(10,20),
                           cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2)
        # 放置時間戳
        cv2.putText(frame_lwpCV,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        (10,frame_lwpCV.shape[0]-10),cv2.FONT_HERSHEY_SIMPLEX,0.35,(0,255,0),2)

    # 如果檢測到
    if text == "Detected" :
        cv2.putText(frame_lwpCV,"Motion: {}".format(text),(10,20),
                           cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),2)
        cv2.putText(frame_lwpCV,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        (10,frame_lwpCV.shape[0]-10),cv2.FONT_HERSHEY_SIMPLEX,0.35,(0,255,0),2)
        # 蔣告警標誌位置為1
        flag=1

    # 判斷告警標誌位
    if flag == 1:
        # 接入一些接口,進行對用戶的警示,微信,丁丁,短信 ...等等
        # 然後將標誌位置為0
        pass

    # 顯示圖像
    cv2.imshow(‘contours‘,frame_lwpCV)
    # 灰度圖像的顯示
    # cv2.imshow(‘dis‘,diff)

    # 添加退出鍵--q
    # 按下退出本次監測
    key = cv2.waitKey(1) & 0xff
    if key == ord(‘q‘):
        break

# 退出後釋放攝像頭
camera.release()
cv2.destroyAllWindows()


# 聲明:該代碼源於騰訊課堂-動腦學院-Python公開課,並加以適當修改

[Python Study Notes]物體運動檢測