Question

I'm trying to use cv::InRange() with a HSV-image. Because the hue value is cyclic I need to process min/max values where the min hue might be bigger than the max hue value. So far I used the following code to calculate the range mask:

cv::Mat InRangeMask(const cv::Mat &hsv, cv::Scalar min, cv::Scalar max)
{
    cv::Mat rangeMask;
    if(min[0]<=max[0])
    {
        cv::inRange(hsv, min, max, rangeMask);
    } 
    else 
    {
        cv::Mat rangeMask2;
        cv::Scalar min1(0, min[1], min[2]);
        cv::Scalar max1(min[0], max[1], max[2]);
        cv::Scalar min2(max[0], min[1], min[2]);
        cv::Scalar max2(179, max[1], max[2]);

        cv::inRange(hsv, min1, max1, rangeMask);
        cv::inRange(hsv, min2, max2, rangeMask2);
        rangeMask |= rangeMask2;
    }
    return rangeMask;
}

But this solution requires twice the time in the else case (in release with optimization). I think there can be a more efficient code with inverting the ranges or inverting the image in some way. But since I'm using a full hsv range and not just the hue channel I have not found a better solution yet.

What would be a more efficient implementation for calculating pixels in a hsv range? I'm sure someone already has a good solution for this problem. Using openCV functions or rewrite the algorithm?

Was it helpful?

Solution

You can always rewrite the algorithm, which isn't that complicated for function inRange.

Another solution could be to simply use inRange when min[0]<=max[0] and otherwise do the following:

  1. slit the channels {hchan,schan,vchan} of your image using cv::split

  2. apply inRange to the three channels and get maskH, maskS, maskV

    • inRange(hchan,max[0],min[0],maskH)
    • inRange(schan,min[1],max[1],maskS)
    • inRange(vchan,min[2],max[2],maskV)
  3. recombine the three masks like this

    • bitwise_and(maskS,maskV,rangeMask)
    • bitwise_not(maskH,maskH)
    • bitwise_and(maskH,rangeMask)

But I personnally think that is an overshoot (and also less efficient than to rewrite the algorithm).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top