且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在OpenCV中设置HSV颜色范围?

更新时间:2023-01-25 09:52:53

您错误地设置了上限和下限,它们必须是:

You have wrongly set the upper and lower bounds, they must be:

greenLower = (50, 0, 50)         # Previously (300, 0, 50)
greenUpper = (300, 128, 250)     # Previously (50, 128,250)

还要确保hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)作为OpenCV遵循BGR约定.

Also make sure that hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) as OpenCV follows the BGR convention.

要在多个范围0~50300~359中对颜色进行分段,可以对两个范围执行两次cv2.inRange(),如下所示:

To segment colors in multiple ranges 0~50 and 300~359, you can perform cv2.inRange() twice for two ranges as:

greenLower1 = (0, 0, 20)         
greenUpper1 = (50, 128, 100)     

greenLower2 = (300, 0, 20)         
greenUpper2 = (359, 128, 100)     

mask1 = cv2.inRange(img_hsv, greenLower1, greenUpper1)
mask2 = cv2.inRange(img_hsv, greenLower2, greenUpper2)

mask = cv2.max(mask1, mask2)