本文實(shí)例為大家分享了python opencv運(yùn)動檢測的具體代碼,供大家參考,具體內(nèi)容如下
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、成都微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了灣里免費(fèi)建站歡迎大家使用!# -*- coding:utf-8 -*- __author__ = 'kingking' __version__ = '1.0' __date__ = '14/07/2017' import cv2 import numpy as np import time camera = cv2.VideoCapture(0) # 參數(shù)0表示第一個攝像頭 # 判斷視頻是否打開 if (camera.isOpened()): print('Open') else: print('攝像頭未打開') background = cv2.imread('img.png',0)#讀入一幅圖像 es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 4)) while True: # 按'q'健退出循環(huán) key = cv2.waitKey(1) & 0xFF # 讀取視頻流 grabbed, img = camera.read() gray1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray1, (21, 21), 0)#可在這添加處理程序 #?。?!等相機(jī)穩(wěn)定后按下W選擇背景 if key == ord('w'): background = gray print '背景已選定' diff = cv2.absdiff(gray, background) binary = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]#二值化閾值處理 dilation = cv2.dilate(binary, es, iterations=2) # 形態(tài)學(xué)膨脹<--可在這添加處理程序 contours, hierarchy = cv2.findContours(dilation.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for c in contours: # 對于矩形區(qū)域,只顯示大于給定閾值的輪廓,所以一些微小的變化不會顯示。 if cv2.contourArea(c) < 1500: continue (x, y, w, h) = cv2.boundingRect(c) # 該函數(shù)計(jì)算矩形的邊界框 cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow('img', img) cv2.imshow('dilation', dilation) if key == ord('q'): break camera.release()#ubuntu一定要釋放相機(jī)資源否則要重啟才能再次使用 cv2.destroyAllWindows()