Wednesday, 19 March 2014

#8c. Object Detection: Morphological Opening and Closing

In our Object Detection application, you may have noticed quite some amount of noise.
When it is supposed to detect red color, it also detects some noise, and gives wrong output,sometimes.


Opening is obtained by eroding an image followed by dilating it. It will have an effect of removing small white regions in the image. Closing is obtained by dilating an image followed by eroding it; this will have the opposite effect. Both these operations are used frequently to remove noise
from an image. Opening removes small white pixels while closing removes small black “holes.”

The OpenCV function morphologyEX()can be used to perform advanced morphological operations such as opening and closing on images. So we can open and close the output of the inRange() function to remove black and white dots by updating the 'main' function:

int main()
{

 VideoCapture cap(0);
 namedWindow("Video");
 namedWindow("Segmentation");

  createTrackbar("0.R\n1.G\n2.B","Segmentation",&rgb_slider, 2 ,on_rgb_trackbar);

 createTrackbar("Low threshold","Segmentation",&low_slider,255,on_low_thresh_trackbar);

 createTrackbar("High threshold","Segmentation",&high_slider,255,on_high_thresh_trackbar);

 while(char(waitKey(1)) != 'q') {
  cap>>frame;
  if(frame.empty())
   break;
  inRange(frame,Scalar(low_b,low_g,low_r),Scalar(high_b,high_g,high_r),frame_threshold);

//Morphological Opening and Closing
  Mat str_el=getStructuringElement(MORPH_RECT,Size(3,3));
  morphologyEx(frame_threshold,frame_threshold,MORPH_OPEN,str_el);
  morphologyEx(frame_threshold,frame_threshold,MORPH_CLOSE,str_el);


  imshow("Video",frame);
  imshow("Segmentation",frame_threshold);
 }

 return 0;
}
---------------------------------------------------------

No comments:

Post a Comment