本文主要實現了伯樂在線上的一個實踐小項目,原文鏈接,用以鞏固opencv視頻操作知識內容。整個項目均有代碼注釋,通俗易懂,短短幾十行就可以達到還算不錯的實現效果,做起來成就感滿滿噠。打開編輯器,一起來感受下opencv+python在CV中的無窮魅力吧 ^_^

1 import argparse 2 import time 3 import imutils 4 import cv2 5 6 # 創建參數解析器並解析參數 7 ap = argparse.ArgumentParser() 8 ap.add_argument("-v", "--video", help="path of the video") 9 # 待檢測目標的最小面積,該值需根據實際應用情況進行調整(原文為500) 10 ap.add_argument("-a", "--min-area", type=int, default=2000, help="minimum area size") 11 args = vars(ap.parse_args()) #@ 12 13 # 如果video參數為空,則從自帶攝像頭獲取數據 14 if args.get("video") == None: 15 camera = cv2.VideoCapture(0) 16 # 否則讀取指定的視頻 17 else: 18 camera = cv2.VideoCapture(args["video"]) 19 20 21 # 開始之前先暫停一下,以便跑路(離開本本攝像頭拍攝區域^_^) 22 print("Ready?") 23 time.sleep(1) 24 print("Action!") 25 26 # 初始化視頻第一幀 27 firstRet, firstFrame = camera.read() 28 if not firstRet: 29 print("Load video error!") 30 exit(0) 31 32 # 對第一幀進行預處理 33 firstFrame = imutils.resize(firstFrame, width=500) # 尺寸縮放,width=500 34 gray_firstFrame = cv2.cvtColor(firstFrame, cv2.COLOR_BGR2GRAY) # 灰度化 35 firstFrame = cv2.GaussianBlur(gray_firstFrame, (21, 21), 0) #高斯模糊,用於去噪 36 37 # 遍歷視頻的每一幀 38 while True: 39 (ret, frame) = camera.read() 40 41 # 如果沒有獲取到數據,則結束循環 42 if not ret: 43 break 44 45 # 對獲取到的數據進行預處理 46 frame = imutils.resize(frame, width=500) 47 gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 48 gray_frame = cv2.GaussianBlur(gray_frame, (21, 21), 0) 49 50 # cv2.imshow('video', firstFrame) 51 # 計算第一幀和其他幀的差別 52 frameDiff = cv2.absdiff(firstFrame, gray_frame) 53 # 忽略較小的差別 54 retVal, thresh = cv2.threshold(frameDiff, 25, 255, cv2.THRESH_BINARY) 55 56 # 對閾值圖像進行填充補洞 57 thresh = cv2.dilate(thresh, None, iterations=2) 58 image, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 59 60 text = "Unoccupied" 61 # 遍歷輪廓 62 for contour in contours: 63 # if contour is too small, just ignore it 64 if cv2.contourArea(contour) < args["min_area"]: 65 continue 66 67 # 計算最小外接矩形(非旋轉) 68 (x, y, w, h) = cv2.boundingRect(contour) 69 cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 2) 70 text = "Occupied!" 71 72 cv2.putText(frame, "Room Status: {}".format(text), (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2) 73 74 cv2.imshow('frame', frame) 75 cv2.imshow('thresh', thresh) 76 cv2.imshow('frameDiff', frameDiff) 77 78 # 處理按鍵效果 79 key = cv2.waitKey(60) & 0xff 80 if key == 27: # 按下ESC時,退出 81 break 82 elif key == ord(' '): # 按下空格鍵時,暫停 83 cv2.waitKey(0) 84 85 # 釋放資源並關閉所有窗口 86 camera.release() 87 cv2.destroyAllWindows()
附上原文實驗結果: