opencv物體圖像移動檢測

# -*-coding:utf-8 -*-  

import cv2
import time
import datetime
import numpy as np 

camera = cv2.VideoCapture(0)

if (camera.isOpened()):
    print('Open')
else:
    print('請打開攝像頭')
#查看視頻size
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, (9, 4)) 
kernel = np.ones((5, 5), np.uint8) 

pre_frame = None

while(1):
    ret, frame = camera.read()
    gray_lwpCV = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #gray_lwpCV = cv2.resize(gray_lwpCV, (500, 500))
    gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)

    #將當前第一幀作爲對比
    if pre_frame is None:
        pre_frame = gray_lwpCV
        continue;
         # absdiff把兩幅圖的差的絕對值輸出到另一幅圖上面來
    img_delta = cv2.absdiff(pre_frame, gray_lwpCV)
    thresh = cv2.threshold(img_delta, 10, 255, cv2.THRESH_BINARY)[1]
    thresh = cv2.dilate(thresh, es, iterations=2)
        # findContours檢測物體輪廓(尋找輪廓的圖像,輪廓的檢索模式,輪廓的近似辦法)
    contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)



    for c in contours:
           # 設置判斷的範圍
        if cv2.contourArea(c) < 1500:
            continue
        else:
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(frame, "當前時間: {}".format(str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) ), (10, 20),
                         cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
            break
    pre_frame = gray_lwpCV
    cv2.imshow("capture", frame)
    cv2.imshow("Frame Delta", img_delta)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

camera.release()
cv2.destroyAllWindows()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章