Saturday, November 19, 2016

How to binarize image.

* Binary image has following steps:
** To convert image to gray scale.
** To check every pixel if greater than threshold, set value to maximum(255), otherwise minimum(0).

#include <cv.hpp>

using namespace cv;
#define THRESHOLD 100

int main( int argc, char** argv )
{
  Mat image;
  image = imread( "resource/lena.png", IMREAD_COLOR );
  Mat Output( image.rows, image.cols, CV_8UC3, Scalar(0, 0, 0) );
  int height = image.rows;
  int width = image.cols;

  for(int row = 0; row < height; row++) {
      for(int col = 0; col < width; col++) {
          uchar val = (image.at<Vec3b>(row, col)[0] * 0.2999 + image.at<Vec3b>(row, col)[1] * 0.587 + image.at<Vec3b>(row, col)[2] * 0.114);

          Output.at<Vec3b>(row, col)[0] = (val > THRESHOLD ? 255 : 0);
          Output.at<Vec3b>(row, col)[1] = (val > THRESHOLD ? 255 : 0);
          Output.at<Vec3b>(row, col)[2] = (val > THRESHOLD ? 255 : 0);
      }
  }

  namedWindow("out", WINDOW_NORMAL);
  imshow("out", Output);

  waitKey(0);

  return 0;
}
Result:

No comments: