0

我希望能够计算检测到的对象中的像素数。我正在使用 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/ 蒙版上 cv2.bitwise_and 全黑图像,但这似乎可能很慢,而且我不知道如何创建这样的全黑和白图像。

那么 TD:LR,你如何计算二进制图像中物体的像素数?

注意:我实际上只是在最大对象之后,只需要像素数,而不是图像。

编辑:不尝试计算检测到的像素总数,我已经这样做了。想要从具有最大数量的对象中检测到的像素数。

4

1 回答 1

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)
于 2016-10-03T05:13:29.420 回答