2016-09-25 75 views
0

我希望能夠計算檢測到的物體中的像素數量。我正在使用cv2.threshold函數。這裏有一些sudo代碼。Python OpenCv2,計算有色物體的輪廓

import cv2 
import numpy as np 
import time 

while True: 
    cam= cv2.VideoCapture(0) 
    while(cam.isOpened()) 
     ret, image = cam.read() 
     image = cv2.GaussianBlur(image, (5,5), 0) 
     Image1 = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) 
     lower= np.array([30,40,40], dtype='uint8') 
     upper= np.array([95,240,240], dtype='uint8') 
     Thresh= cv2.inRange(Image1, lower, upper) 

從這裏開始,我不知道如何計算我的對象的像素。你如何找到二進制圖像的輪廓?我想這可能是cv2.bitwise_and一個完整的黑色圖像在Thresh/mask上,但是看起來它可能很慢,而且我也不知道如何創建一個完全黑白的圖像。

所以TD:LR,你如何計算二值圖像中物體的像素數?

注意:我實際上只是在最大的對象之後,只需要像素的數量,而不是圖像。

編輯:不試圖計算檢測到的像素總數,我已經這樣做了。希望從數量最多的對象中檢測到的像素數量。

+1

[Python中的圖像與OpenCV的黑色像素的計數值(可能的重複http://stackoverflow.com/questions/32590932/count-number- python-with-opencv) – Miki

+0

做標籤,http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage .measurements.label.html。獲取最大對象的標籤並計算像素np.sum(label_image == label)。 – GpG

+0

以前從未使用過scipy,但它可以以高效的速度工作。謝謝! –

回答

0

這是我做的

import cv2 
import numpy as np 
import time 
from scipy.ndimage import (labeled_comprehension, label, measurements, generate_binary_structure) # new import 

while True: 
    cam= cv2.VideoCapture(0) 
    while(cam.isOpened()) 
     ret, image = cam.read() # record image 
     image = cv2.GaussianBlur(image, (5,5), 0) # blur to remove noise 
     Image1 = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert to better color scheme 
     lower= np.array([30,40,40], dtype='uint8') # low green 
     upper= np.array([95,240,240], dtype='uint8') # high green 
     Thresh= cv2.inRange(Image1, lower, upper) # returns array with 255 as pixel if in threshold 
     struct = generate_binary_structure(2,2) # seems necessary for some reason 
     Label, features = label(Thresh, struct) # label is object, features is number of objects 
     Arange = np.arange(1, features+1) # seems necessary for some reason 
     Biggest = sorted(labeled_comprehension(Thresh, Label, Arange, np.sum, float, -1))[features-1]//255 # counts and organises the objects based on size. [features-1] means last object, ie: biggest. //255 because that's each pixel work (from thresh)