Saturday, July 26, 2014

different stages of using OpenCV

1: read in images.
Mat src = imread("and.png");

2: convert to a gray image.

 Mat gray;
cvtColor(src, gray, CV_BGR2GRAY);
3: find edges. There are two ways: threshold and canny. This step is optional. If the picture is only black and white, then this step is not necessary. We can just use findContours.
Mat th; Mat bw;
//method 1:  threshold(gray, th,125, 255,THRESH_BINARY);

//method 2:  Canny(gray, bw, 100, 200); 


       Note the differences between the above two images.
4: find contours and draw contours.
4.1:  findContours(th, contours, hierarchy,CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
 Note the red rectangle. If we change :
threshold(gray, th,125, 255,THRESH_BINARY);
to
threshold(gray, th,125, 255,THRESH_BINARY_INV);
You will not see that red  rectangle.

   4.2: findContours(bw, contours2, hierarchy2,CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
Why do we get 4 contours instead of 2 contours since we only two shapes in the canny output?
Because Canny creates two contours for each edge, one outside and one inside of that edge.


4: write out the image.

imwrite("output.png", color); 

No comments:

Post a Comment