如何在 python opencv 中获取 hsv 颜色的低值和高值

How to get low and high values of hsv color in python opencv

我正在尝试在 python opencv 中检测几种颜色。为此,我需要定义低和高 hsv 值,以便代码可以读取它并检测颜色。现在我面临的问题是如何获得高和低 hsv 颜色。我指的是下图

我需要检测这件夹克,因此需要输入它的高低 hsv。为此,我得到了对此 code 的引用,它允许 select 图像的任何部分,并将为其输出高和低 hsv 值。但据我所知,hsv 值不能大于 100,但是这段代码和大多数其他在线代码给出的 hsv 值都大于 100,这让我很困惑这些值如何大于100.

任何人都可以解释一下我们如何获得低和高 hsv 值的值

试试下面的代码:

import cv2
import numpy as np

img = cv2.imread("jacket.jpg")

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# mask of green (36,25,25) ~ (86, 255,255)
mask = cv2.inRange(hsv, (36, 25, 25), (70, 255,255))

green = cv2.bitwise_and(img,img, mask= mask)    

cv2.imshow('Image', green)
cv2.waitKey(0)
cv2.destroyAllWindowss()

输出:

查看 this Whosebug 讨论如何正确 select 颜色检测的上下 hsv 值。

Couldnt find the resource but found something like this and made it useful, thanks to the author

import cv2
import imutils  
import numpy as np  

image_hsv = None   # global
pixel = (20,60,80) # some stupid default

# mouse callback function
def pick_color(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        pixel = image_hsv[y,x]

        #you might want to adjust the ranges(+-10, etc):
        upper =  np.array([pixel[0] + 10, pixel[1] + 10, pixel[2] + 40])
        lower =  np.array([pixel[0] - 10, pixel[1] - 10, pixel[2] - 40])
        print(pixel, lower, upper)

        image_mask = cv2.inRange(image_hsv,lower,upper)
        cv2.imshow("mask",image_mask)

def main():
    import sys
    global image_hsv, pixel # so we can use it in mouse callback

    image_src = cv2.imread("myimage.jpeg")  # pick.py my.png
    image_src = imutils.resize(image_src, height=800)
    if image_src is None:
        print ("the image read is None............")
        return
    cv2.imshow("bgr",image_src)

    ## NEW ##
    cv2.namedWindow('hsv')
    cv2.setMouseCallback('hsv', pick_color)

    # now click into the hsv img , and look at values:
    image_hsv = cv2.cvtColor(image_src,cv2.COLOR_BGR2HSV)
    cv2.imshow("hsv",image_hsv)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__=='__main__':
    main()

Image loaded will look like this:

After clicking on the ball you will get an image like,

And finally: true BGR value, lower and upper HSV boundaries will be printed in the terminal as follows,