opencv

Thresholding image in OpenCV for a range of max and min values


I like to threshold an image within a range max and min value and fill the rest with 255 for those pixel values out of that range. I can't find such threshold in OpenCV document here. Thanks


Solution

  • The basic:

    threshold(src, dst, threshold value, max value, threshold type);
    

    where

    src_gray: Our input image
    dst: Destination (output) image
    threshold_value: The thresh value with respect to which the thresholding operation is made
    max_BINARY_value: The value used with the Binary thresholding operations (to set the chosen pixels)
    threshold_type: One of the 5 thresholding operations. 
    

    so for example,

    threshold(image, fImage, 125, 255, cv::THRESH_BINARY);
    

    means every value below 125, will be set to zero, and above 125 to the value of 255.

    If what you are looking for is to have a particular range, for instance 50 to 150, I would recommend you do a for loop, and check and edit the pixels yourself. It is very simple. Take a look at this c++ code of mine:

    for (int i=0; i< image.rows; i++)
        { 
            for (int j=0; j< image.cols; j++)
            {
                int editValue=image.at<uchar>(i,j);
    
                if((editValue>50)&&(editValue<150)) //check whether value is within range.
                {
                    image.at<uchar>(i,j)=255;
                }
                else
                {
                    image.at<uchar>(i,j)=0;
                }
            }
        }
    

    Hope I solved your problem. Cheers(: Do comment if you need more help.