Search code examples
c++opencvthreshold

Thresholding image in OpenCV of min value


I want to use cv::threshold function because it is well optimized rather than looping through the whole image myself.. however it doesn't have a thresholding to a minimum value. That the options available:

enter image description here

What I want is to set pixels that are smaller than a certain value to that value, example:

image.at<float>(j,i) > 0.1f ? image.at<float>(j,i): 0.1f;

Can I do that without using loops?

I tried that:

image.setTo(0.1, image < 0.1);

But it is saying that:

 error: no match for ‘operator<’ (operand types are ‘const cv::UMat’ and ‘double’)

PS: my images are of type cv::UMat


Solution

  • Note that for a number x between 0 and 255 the equivalence max(x, thresh) == 255 - min(255-x, 255-thresh) holds and the results stay within [0, 255].

    So you can (i) invert the image, (ii) build the max-threshold by 255-thresh, and (iii) invert again.

    Note that mathematically for any constant a it holds that max(x, thresh) == a - min(a-x, a-thresh), e.g., max(x, thresh) == -min(-x, -thresh). The last one is the preferred one for floating-point data.