Opencv python检测对象的颜色是白色还是黑色



我是新的opencv,我已经设法检测对象并在它周围放置ROI,但我无法管理它,所以检测对象是黑色还是白色。我发现了一些我认为,但我不知道这是否是正确的解决方案。如果是黑色或白色,函数应该返回True或False。有人有过这样的经历吗?

def filter_color(img):
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        lower_black = np.array([0,0,0])
        upper_black = np.array([350,55,100])
        black = cv2.inRange(hsv, lower_black, upper_black)

如果你确定ROI基本上是黑色或白色的,并且不担心错误识别某些东西,那么你应该能够平均ROI中的像素并检查它是否高于或低于某个阈值。

在下面的代码中,在使用较新的numpy方法设置ROI之后,您可以将ROI/图像传递到该方法中,就像传递完整的图像一样。

<标题> 复制粘贴样本
import cv2
import numpy as np

def is_b_or_w(image, black_max_bgr=(40, 40, 40)):
    # use this if you want to check channels are all basically equal
    # I split this up into small steps to find out where your error is coming from
    mean_bgr_float = np.mean(image, axis=(0,1))
    mean_bgr_rounded = np.round(mean_bgr_float)
    mean_bgr = mean_bgr_rounded.astype(np.uint8)
    # use this if you just want a simple threshold for simple grayscale
    # or if you want to use an HSV (V) measurement as in your example
    mean_intensity = int(round(np.mean(image)))
    return 'black' if np.all(mean_bgr < black_max_bgr) else 'white'
# make a test image for ROIs
shape = (10, 10, 3)  # 10x10 BGR image
im_blackleft_white_right = np.ndarray(shape, dtype=np.uint8)
im_blackleft_white_right[:, 0:4] = 10
im_blackleft_white_right[:, 5:9] = 255
roi_darkgray = im_blackleft_white_right[:,0:4]
roi_white = im_blackleft_white_right[:,5:9]

# test them with ROI
print 'dark gray image identified as: {}'.format(is_b_or_w(roi_darkgray))
print 'white image identified as: {}'.format(is_b_or_w(roi_white))
# output
# dark gray image identified as: black
# white image identified as: white

我不知道这是否是正确的方法,但它适用于我。

black = [0,0,0]
Thres = 50
h,w = img.shape[:2]
black = 0
not_black = 0
for y in range(h):
    for x in range(w):
        pixel = img[y][x]
        d = math.sqrt((pixel[0]-0)**2+(pixel[1]-0)**2+(pixel[2]-0)**2)
        if d<Thres:
            black = black + 1
        else:
            not_black = not_black +1

这个对我有用,但就像我说的,不知道这是不是正确的方法。它需要大量的处理能力,因此我定义了一个小得多的ROI。

相关内容

  • 没有找到相关文章

最新更新