Search code examples
matlabimage-processingbinarylabelbounding-box

Labeling object in a binary image MATLAB


I am trying to label white objects in a binary image using MATLAB. Basically, my aim is to detect water bodies in a aerial map image and then convert the cimage to binary and then label the bodies. Here is an image example of my output after detecting the bodies and converting to binary. How can I now possibly create a create rectangle around the white objects and label them with text(using connected components)? Thank you!

enter image description here


Solution

  • Try this -

    %%// Read in the image file
    img = im2bw(imread(FILE));
    
    %%// Get bounding box stats
    stats = regionprops(bwlabel(img),'Area','Centroid','Perimeter','BoundingBox');
    Boxes=cat(1,stats.BoundingBox);
    
    %%// Placeholder to store the final result
    maskm = false(size(img,1),size(img,2));
    
    for k1 = 1:size(Boxes,1)
    
        %%// Initialize a mask representing each bounding box
        mask1 = false(size(img,1),size(img,2));
    
        %%// Get the coordinates of the boxes
        starty = round(Boxes(k1,1));
        stopy = starty+round(Boxes(k1,3))-1;
        startx = round(Boxes(k1,2));
        stopx = startx+round(Boxes(k1,4))-1;
    
        %%// Finaly create the mask
        mask1(startx:stopx,starty:stopy) = true;
        maskm = maskm + imdilate(edge(mask1,'sobel'),strel('disk',2));
    end
    
    %%// Get the boxes around the original blobs
    maskm = maskm + img;
    figure,imshow(maskm);
    

    Output

    enter image description here

    Look into text on how to label the boxes.