我希望能够计算检测到的对象中的像素数。我正在使用cv2.threshold函数。这是一些sudo代码。
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)
从现在开始,我不知道如何计算我的物体的像素。你如何找到二进制图像的轮廓?我想可以在Thresh / mask上使用cv2.bitwise_和一个完整的黑色图像,但这似乎可能很慢,而且我也不知道如何创建像这样的完全黑白图像。 / p>
所以TD:LR,你如何计算二进制图像中对象的像素数?
注意:我实际上只是在最大的物体之后,只需要像素数,而不是图像。
编辑:我没有尝试计算检测到的像素总数,我已经做过了。想要从具有最大数量的对象中检测到的像素数。
答案 0 :(得分: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)