我是opencv的新手,我已经设法检测到对象并在其周围放置了一个ROI,但我无法管理它,因此检测对象是黑色还是白色。我发现了一些我认为但我不知道这是否是正确的解决方案。如果它是黑色或白色,该函数应返回True of 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)
答案 0 :(得分:1)
如果您确定ROI基本上是黑色或白色并且不担心错误识别某些内容,那么您应该能够平均ROI中的像素并检查它是否高于或低于某个阈值。< / p>
在下面的代码中,设置ROI using the newer numpy method后,您可以将roi / image传递给方法,就像传递完整图像一样。
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
答案 1 :(得分:-1)
我不知道这是否是正确的做法,但它对我有用。
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。 Thres目前是硬编码的......