git:https://github.com/linyi0604/Computer-Vision
使用mog2算法進行背景分割
1 # coding:utf-8
2
3 import cv2 4
5 # 獲取攝像頭對象
6 cap = cv2.VideoCapture(0) 7 # 背景分割器對象
8 mog = cv2.createBackgroundSubtractorMOG2() 9
10 while True: 11 ret, frame = cap.read() 12 fgmask = mog.apply(frame) 13 cv2.imshow("frame", fgmask) 14 if cv2.waitKey(5) & 0xff == ord("q"): 15 break
16
17 cap.release() 18 cv2.destroyAllWindows()
使用knn進行背景分割 順便檢測運動物體
1 # coding:utf-8
2
3 import cv2 4
5 # 獲取攝像頭
6 camera = cv2.VideoCapture(0) 7 # 獲取背景分割器對象
8 bs = cv2.createBackgroundSubtractorKNN(detectShadows=True) 9
10 while True: 11 # 讀取幀
12 ret, frame = camera.read() 13 # 獲取前景
14 fgmask = bs.apply(frame) 15 # 對前景二值化
16 th = cv2.threshold(fgmask.copy(), 244, 255, cv2.THRESH_BINARY)[1] 17 # 膨脹運算
18 dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2) 19 # 檢測輪廓
20 image, contours, hier = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 21 # 將輪廓畫在原圖像上
22 for c in contours: 23 x, y, w, h = cv2.boundingRect(c) 24 cv2.rectangle(frame, (x, y), (x+w, y+h), (2555, 255, 0), 2) 25 # 顯示前景
26 cv2.imshow("fgmask", fgmask) 27 # 顯示二值化
28 cv2.imshow("thresh", th) 29 # 顯示帶有輪廓的原圖
30 cv2.imshow("detection", frame) 31 if cv2.waitKey(5) & 0xff == ord("q"): 32 break
33
34 cv2.destroyAllWindows() 35 camera.release()