Search code examples
image-processingopencvjavacv

How to identify contour which are not directly separated from each other?


Please can some one explain how to identify square shape of contours which are not exactly separated each other. For example I need to identify the number of squares in below image and the x,y coordinates of their edges. I try to go through this question but it didn't work for me.

enter image description here

So please can some one explain this using simple code example.

This is the image that I can generated can you please explain how to identify above squares in this image.

enter image description here

So please be kind enough to explain this.


Solution

  • You have to use fact, that red component of each square equals 255, and do the threshold. Here's what I've done:

    1. Do a red color segmentation: enter image description here

    2. Do dilatation (to remove holes): enter image description here

    3. (Optional) Do a check if each contour is a square.

    Code:

    Mat src = imread("input.png"), red;
    extractChannel(src, red, 2);
    
    threshold(red, red, 254, 255, THRESH_BINARY);
    
    Mat element = getStructuringElement(MORPH_RECT, Size( 2, 2 ), Point( 1, 1 ));
    dilate(red, red, element);