#include "opencv2/opencv.hpp"

void dilatation(IplImage *img)
{
  if (img->nChannels!=1)
    cvCvtColor(img,img,CV_BGR2GRAY);

  cvThreshold(img,img,120,255,CV_THRESH_BINARY);

  for(int i=0;i<img->width;i++)  
    for(int j=0;j<img->height;j++)
      if (cvGet2D(img,i,j).val[0]==255)
      {
        if (i!=0) 
          cvSet2D(img,i-1,j,cvScalar(255));
        else
          if (i!=img->width-1)
            cvSet2D(img,i+1,j,cvScalar(255));
        cvSet2D(img,i,j,cvScalar(255));
      }
}

int main(int argc,char**argv)
{

  IplImage *img=cvLoadImage("biohazard.png",CV_LOAD_IMAGE_GRAYSCALE);
  if (!img) return EXIT_FAILURE;
  IplImage *copy=cvCloneImage(img);

  dilatation(copy); 
  cvShowImage("dilatation",copy);

  IplConvKernel *se=cvCreateStructuringElementEx(3,1,1,0,CV_SHAPE_RECT);
  cvDilate(img,copy,se);
  cvShowImage("Dilate",copy);
  cvErode(img,copy,se,3);
  cvShowImage("Erode",copy);
  
  cvErode(img,copy,se);
  cvDilate(copy,copy,se);
  cvShowImage("Erode&Dilate",copy);
  cvMorphologyEx(img,copy,NULL,se,CV_MOP_OPEN);
  cvShowImage("Open",copy);

  cvDilate(img,copy,se);
  cvErode(copy,copy,se);
  cvShowImage("Dilate&Erode",copy);
  cvMorphologyEx(img,copy,NULL,se,CV_MOP_CLOSE);
  cvShowImage("Close",copy);

  cvWaitKey();

  cvReleaseImage(&img);
  cvReleaseImage(&copy);
  cvReleaseStructuringElement(&se);
  cvDestroyAllWindows();
  return EXIT_SUCCESS;
}
