MATLAB: How to extract only object with white background using bounding box in MatLab

active contoursbackground removalbounding boxbwareaopencroppingImage Processing Toolboximage segmentationregionprops

Just to clarify what you would like to do: you would like to get bounding boxes on objects extracted from an image, but you only want the object itself and not what is in the background? For example, in the image you provided, you would like to extract bounding boxes around each of the four coins?

Best Answer

I think what you are looking for is activecontour. Active contours allow you to separate an image into foreground and background.
Using the image of coins you provided, the following code generates a binary image bw in which white pixels belong to the foreground (coins) and black pixels belong to the background:
% Open image
I = imread('coins.jpg');
% Convert to grayscale
I = rgb2gray(I);
% Show image
figure(1);
imshow(I)
title('Image with objects')
% mask is the initial contour state
mask = zeros(size(I));
mask(25:end-25,25:end-25) = 1;
% Show mask
figure(2);
imshow(mask);
title('Initial contour location')
% bw is a mask of the detected objects
numIter = 2500;
bw = activecontour(I, mask, numIter);
% Show detected objects
figure(3);
imshow(bw);
title('Detected objects')
When using activecontour, keep in mind that the default number of iterations is 100. Depending on the image you are working on, you might want to change that to a larger number of iterations. In the example code above I chose 2500 and all four coins are successfully separated.
Then, you can use the bwconncomp function to find each coin in the image as a connected component. However, noise might be present in bw after running active contours. You can use the bwareaopen function to perform a morphological opening on the binary image bw and remove connected components that have less than a certain number of pixels.
I included the entire script (extractCoins.m) with all operations, from opening the image to cropping the coins from their background and displaying them. This is the final result: