傳統的前景背景分割方法有GrabCut,分水嶺算法,當然也包括一些閾值分割的算法。但是這些算法在應用中往往顯得魯棒性較弱,達不到一個好的分割效果。
現代的背景分割算法融入了機器學習的一些方法來提高分類的效果。如KNN,混合高斯(MOG2),Geometric Multigrid。這些算法的基本原理就是對每一幀圖像的環境進行學習,從而推斷出背景區域。
opencv的BackgroundSubtractor提供了這些現代的背景分割算法。
1.思想
1.定義1個KNN背景分割器對象 2.定義視頻對象 while True: 3.一幀幀讀取視頻 4.計算前景掩碼 5.二值化操作 6.膨脹操作 7.查找輪廓 8.輪廓篩選 9.畫出輪廓(在原圖像) 10.顯示圖像幀,
2。代碼
#-*- coding:utf-8 -*- import cv2 import numpy as np # 1.常見一個BackgroundSubtractorKNN接口 bs = cv2.createBackgroundSubtractorKNN(detectShadows=True) #2.讀取視頻 camera = cv2.VideoCapture('traffic.flv') #定義卷積核圓形 kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)) while True: ret,frame = camera.read() #3. apply()函數計算了前景掩碼 fgmask = bs.apply(frame) #4. 獲得前景掩碼(含有白色值以及陰影的灰色值),通過設定閾值將非白色(244~255)的所有像素都設為0,而不是1; th = cv2.threshold(fgmask.copy(),244,255,cv2.THRESH_BINARY)[1] #二值化操作 dilated = cv2.dilate(th,kernel,iterations =2) #5.膨脹操作 #cv2.getStructuringElement 構建一個橢圓形的核 #3x3卷積核中有2個1那就設置為1 #6. findContours函數參數說明cv2.RETR_EXTERNAL只檢測外輪廓, # cv2.CHAIN_APPROX_SIMPLE只存儲水平,垂直,對角直線的起始點。 image,contours,hier = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #查找輪廓 for c in contours: #從list列表取出每個輪廓 if cv2.contourArea(c) < 1500: #進行輪廓篩選 輪廓面積小於1500 continue (x,y,w,h) = cv2.boundingRect(c) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow("mog",fgmask) cv2.imshow("thresh",th) cv2.imshow("detection",frame) if cv2.waitKey(100) & 0xff == ord("q"): break camera.release() cv2.destroyAllWindows()
# coding:utf-8 import cv2 import numpy as np #from MyCvUtils import MyCvUtils #datapath = "D:/imgData/video/" bs = cv2.createBackgroundSubtractorKNN(detectShadows=True) camera = cv2.VideoCapture("traffic.flv") ret, frame = camera.read() while True: ret, frame = camera.read() # 計算前景掩碼,包含 前景的白色值 以及 陰影的灰色值 fgmask = bs.apply(frame) # 前景區域二值化,將非白色(0-244)的非前景區域(包含背景以及陰影)均設為0,前景的白色(244-255)設置為255 th = cv2.threshold(fgmask.copy(), 244, 255, cv2.THRESH_BINARY)[1] # 前景區域形態學處理 th = cv2.erode(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2) dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (8, 3)), iterations=2) # 繪制前景圖像的輪廓矩形 image, contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours: # 對輪廓設置最小區域,對檢測結果降噪 if cv2.contourArea(c) > 1000: (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 0), 2) cv2.imshow("mog", fgmask) cv2.imshow("thresh", th) cv2.imshow("diff", frame & cv2.cvtColor(fgmask, cv2.COLOR_GRAY2BGR)) cv2.imshow("detection", frame) if (cv2.waitKey(30) & 0xFF) == 27: break if (cv2.waitKey(30) & 0xFF) == ord('q'): break camera.release() cv2.destroyAllWindows()
3.效果圖
4.源碼KNN
def createBackgroundSubtractorKNN(history=None, dist2Threshold=None, detectShadows=None): # real signature unknown; restored from __doc__ """ createBackgroundSubtractorKNN([, history[, dist2Threshold[, detectShadows]]]) -> retval . @brief Creates KNN Background Subtractor . @param history
Length of the history. . @param dist2Threshold
Threshold on the squared distance between the pixel and the sample to decide whether a pixel is close to that sample. This parameter does not affect the background update. . @param detectShadows
If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false. """ pass
@簡單創建KNN背景減法器 @param歷史 歷史長度。 @param dist2threshold 閾值像素和樣本之間的平方距離,以決定像素是否接近該樣本。此參數不影響后台更新。 @param detectshadows 如果為真,該算法將檢測陰影並標記它們。它會稍微降低速度,所以如果您不需要這個特性,請將參數設置為false。