Converting a single BGR color with cvtColor and using the result to extract that color from image

前端 未结 1 1648
不思量自难忘°
不思量自难忘° 2021-01-22 03:40

I\'m using c++ but answers in python are fine too.

I need to convert a known BGR color to HSV in order to use the cv::inRange method which allows you to extract a certai

相关标签:
1条回答
  • 2021-01-22 04:30

    Your second conversion is correct (well, if you truncate to int instead of rounding).

    You can always just do the actual calculations for the value as given in the OpenCV docs for cvtColor.

    This is the exact formula linked written in Python. Sorry it's not C++ but I wrote it as basic as possible so it was followable for someone in any other language:

    b, g, r = 126, 105, 98
    
    b = b/255
    g = g/255
    r = r/255
    
    v = max([b, g, r])
    
    if v is 0:
        s = 0
    else: 
        s = (v-min([b, g, r]))/v
    
    
    if v is r:
        h = 60*(g-b)/(v-min([b,g,r]))
    elif v is g:
        h = 120 + 60*(b-r)/(v-min([b,g,r]))
    elif v is b:
        h = 240 + 60*(r-g)/(v-min([b,g,r]))
    
    if h < 0:
        h = h + 360
    
    v = np.round(255*v).astype(int)
    s = np.round(255*s).astype(int)
    h = np.round(h/2).astype(int)
    
    print(h,s,v)
    

    113 57 126

    There are a few different methods you can employ to get good automatic values for color filtering. One method I like is to select an area that is the color you want, and finding the standard deviation and mean of those color values. That way you can easily set the lower and upper bounds of the inRange() function as mean-stddev and mean+stddev respectively. Or you can be less restrictive and multiply your standard deviation by some scalar, and you could choose which direction to be more or less choosy in. E.g., lowerb = mean - 3*stddev and upperb = mean + 1.5*stddev.

    This can be super useful when say you have multiple ROIs with an object in the middle that you care about. You can filter out the colors that are in the border of each ROI separately using the mean and standard deviation of the border pixels!

    0 讨论(0)
提交回复
热议问题