Reputation: 3185
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?
Upvotes: 1
Views: 881
Reputation: 8980
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:
slit the channels {hchan,schan,vchan}
of your image using cv::split
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)
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).
Upvotes: 2