2015-07-13 473 views
2

我在Python中使用opencv(cv2模塊)來識別視頻中的對象。在每一幀中,我想提取一個特定的區域,也就是輪廓。從opencv docs學習後,我有下面的代碼片段:如何在Python中使用opencv使用輪廓遮罩視頻幀

 # np is numpy module, contours are expected results, 
     # frame is each frame of the video 

     # Iterate through the contours. 
     for contour in contours: 
      # Compute the bounding box for the contour, draw 
      # it on the frame, and update the text. 
      x, y, w, h = cv2.boundingRect(contour) 

      # Find the mask and build a histogram for the object. 
      mask = np.zeros(frame.shape[:2], np.uint8) 
      mask[y:h, x:w] = 255 
      masked_img = cv2.bitwise_and(frame, frame, mask = mask) 
      obj_hist = cv2.calcHist([masked_img], [0], None, [256], [0, 256]) 

然而,當我使用matplotlib展現masked_img,它返回一個黑暗的圖像。 obj_hist只有一個數字大於0的元素,這是第一個元素。哪裏不對?

+0

請閱讀[問] – boardrider

+0

@boardrider我已編輯它,希望這可以幫助您瞭解我的問題:-) – user4394476

+0

您是否已驗證「輪廓」包含任何內容? –

回答

2

問題是你在掩碼中設置值的方式。特別是這一行:

mask[y:h, x:w] = 255 

您正在嘗試使用y:hx:w設立面膜片成圖像的每個層面。冒號的左邊是起始行或列,冒號的右邊表示行或列的結尾。鑑於您從y開始,您需要偏移量h使用相同的參考y ...同樣適用於xw

做結腸的正確值小於左邊的切片不會以任何方式修改數組,這就是爲什麼你沒有得到任何輸出,因爲當它最初是所有的時候你並沒有修改掩碼零。

你大概的意思做:

mask[y:y+h, x:x+w] = 255 

這將正確設置由cv2.boundingRect給白(255)適當的區域。

+1

這正是我正在尋找的,非常感謝! – user4394476

+0

@ user4394476 - 我的榮幸:)祝你好運! – rayryeng