2017-04-09 168 views
1

使用HSV顏色,當我試圖執行基於顏色與cv2.inRange對象檢測困惑(Python 2.7版)。使用BGR顏色時,一切看起來都很好。然而,當我映射BGR顏色HSV,我不能得到正確的面具。見下面的例子:在HSVOpenCV的 - 蟒蛇 - 在cv2.inRange

# first convert the img, and the associated lower and upper bound to HSV 
hsv_img_test = cv2.cvtColor(img_test, cv2.COLOR_BGR2HSV) 
lower_hsv = cv2.cvtColor(np.uint8([[[b-step,g-step,r-step]]]), cv2.COLOR_BGR2HSV) 
upper_hsv = cv2.cvtColor(np.uint8([[[b+step,g+step,r+step]]]), cv2.COLOR_BGR2HSV) 


plt.figure(figsize=(20,10)) 
plt.subplot(1,2,1) 
plt.imshow(cv2.cvtColor(hsv_img_test, cv2.COLOR_BGR2RGB)) 

# apply threshold on hsv image 
mask = cv2.inRange(hsv_img_test, lower_hsv, upper_hsv) 
plt.subplot(1,2,2) 
plt.imshow(mask, cmap='gray') 

mario_hsv

在BGR

img_test = cv2.imread("test_img/mario.jpeg") 
#define color range for object detection 
step = 10 
r,g,b = 203, 31, 25 #red 
lower_bgr = np.uint8([b-step, g-step, r-step]) 
upper_bgr = np.uint8([b + step, g + step, r + step]) 

# plot mario in BGR and corresponding mask 
plt.figure(figsize=(20,10)) 
plt.subplot(1,2,1) 
plt.imshow(cv2.cvtColor(img_test, cv2.COLOR_BGR2RGB)) 


mask = cv2.inRange(img_test, lower_bgr, upper_bgr) 
plt.subplot(1,2,2) 
plt.imshow(mask, cmap='gray') 

mario_bgr

2)閾值(不正常

1)閾值)..這顯然不正確。我無法弄清楚代碼中的錯誤,任何幫助都將不勝感激!

回答

1

似乎意外的行爲來自UINT8陣列格式。我沒弄明白的確切原因,但你應該使用無符號整數(例如:0 - 1 = 255)小心操作。

最後,我想我成功地獲得結果,你可能會尋找:

# first convert the img to HSV 
img_test_hsv = cv2.cvtColor(img_test, cv2.COLOR_BGR2HSV) 

# convert the target color to HSV 
target_color = np.uint8([[[b, g, r]]]) 
target_color_hsv = cv2.cvtColor(target_color, cv2.COLOR_BGR2HSV) 

# boundaries for Hue define the proper color boundaries, saturation and values can vary a lot 
target_color_h = target_color_hsv[0,0,0] 
tolerance = 2 
lower_hsv = np.array([max(0, target_color_h - tolerance), 10, 10]) 
upper_hsv = np.array([min(179, target_color_h + tolerance), 250, 250]) 

plt.figure(figsize=(20,10)) 
plt.subplot(1,2,1) 
plt.imshow(cv2.cvtColor(img_test_hsv, cv2.COLOR_HSV2RGB)); 

# apply threshold on hsv image 
mask = cv2.inRange(img_test_hsv, lower_hsv, upper_hsv) 
plt.subplot(1,2,2) 
plt.imshow(mask, cmap='gray'); 

另一點要考慮的是不同的色彩空間RGB和HSV的拓撲結構的差異。 RGB空間中的框不會轉換爲HSV座標中的框。請參考以下維基百科的文章: HSL ans HSV Color Spaces

+0

這工作如果'target_color_h'是一個符號類型。要在保存方面,也許用'最大(公差,target_color_h) - tolerance' – Kjell