title: local thresholding implementation in C++ / OpenCV
body: <p>I would like to implement a local thresholding algorithm and I require your expertise. </p>
  
  <p>my images are resized to 600x400, grayscale.</p>
  
  <p>Basic Thought process on localizing: </p>
  
  <ul>
  <li>Segment the images using a 9x9 ROI taken at each pixel and calculating the maximum intensity in the region. </li>
  <li><p>create a 9x9 Kernel.</p>
  
  <p>condition:</p>
  
  <ul>
  <li>if the center pixel of the mask is above 50% of the maximum intensity, set the center pixel true.(apply mask)</li>
  </ul></li>
  </ul>
  
  <p>my question to you:</p>
  
  <ul>
  <li><p>How should I pick my kernel/mask ?</p>
  
  <pre><code>  cv::Mat ROI;
    cv::Mat mask(input.size(),CV_8UC1, cv::Scalar::all(0)); // create mask of 0s at first
    const int kerneldepth = 1;
    const int kernelsize = 9;
    cv::Mat kernel = cv::Mat::ones( kernelsize, kernelsize, CV_8UC1 );
  
  
  //take ROI of 9x9 and apply a threshold
  
  for( double x = 9; x &lt; input.cols -9; x++ ){
       for( double y = 9 ; y &lt; input.rows - 9 ; y++ ){
  
          try{
            double x_left = x - 4;
            double x_right = x + 4;
            double y_up = y + 4;
            double y_down = y - 4;
            double maxVal;
            double minVal;
            cv::Point anchor(kernelsize/2,kernelsize/2);
  
            cv::Rect ROI = cv::Rect(x_left,y_down,9,9);
            cv::Mat ROI_Mat = input(ROI);                                // a new matrix for ROI
            cv::Scalar avgPixelIntensity = cv::mean( ROI_Mat );          // calculate mean
            cv::minMaxLoc(ROI_Mat,&amp;minVal,&amp;maxVal);
  
            if( input.at&lt;uchar&gt;(x,y) &gt;= 0.5*maxVal){
  
            cv::filter2D(input,mask,-1,kernel,anchor,0);
      } else { break;}
  
      }
  
      catch (cv::Exception &amp;e){
  
          e.what();
      }
  
  
     }
  
    *****************************UPDATED CODE: ******************************************
  
      applyLocalThresh(cv::Mat &amp;src, cv::Mat&amp; out){
        double maxVal, minVal;
        cv::Mat output;
        int top, bottom, left , right;
        int borderType = cv::BORDER_CONSTANT;
        cv::Scalar value;
        top = (int) (9); bottom = (int) (9);
        left = (int) (9); right = (int) (9);
        output = src;
        out = src;
        value = 0;
        cv::copyMakeBorder(src,output,top,bottom,left,right,borderType,value);
  
       for(int y = 9; y &lt; src.rows; y++) {
  
          for(int x = 9; x &lt; src.cols; x ++) {
  
                  cv::Mat ROI = src(cv::Rect(cv::Point(x-4,y-4),cv::Size(9,9)));
                  cv::minMaxLoc(ROI,&amp;minVal,&amp;maxVal);
  
          if(src.at&lt;uchar&gt;(cv::Point(x-4,y-4)) &gt;= 0.6*maxVal){
  
          out.at&lt;uchar&gt;(cv::Point(x-4,y-4)) = 255;
      }else{
          out.at&lt;uchar&gt;(cv::Point(x-4,y-4));
  
          }
      }
  }
   }
  </code></pre></li>
  </ul>