There are several ways to remove the background of an image using Matlab, but one common approach is to use the image segmentation algorithm called GrabCut. Here are the steps to follow:
imread
function.
img = imread('image.jpg');
roipoly
function or automatically using a segmentation algorithm such as imsegkmeans
. In this example, we'll use the imrect
function to create a rectangular mask around the object we want to keep.
mask = zeros(size(img,1), size(img,2)); roi = imrect(gca, [x y width height]); % adjust the rectangle to fit your object pos = getPosition(roi); xmin = round(pos(1)); ymin = round(pos(2)); xmax = round(pos(1)+pos(3)); ymax = round(pos(2)+pos(4)); mask(ymin:ymax, xmin:xmax) = 1;
grabcut
function to segment the image into foreground and background regions. This function requires an initial estimate of the background and foreground pixels, which can be set manually or automatically. In this example, we'll use the automatic method based on the mask we created in step 2.
foregroundPixels = find(mask); backgroundPixels = find(~mask); [L,~] = grabcut(img,mask,foregroundPixels,backgroundPixels,'NumIter',5);
img(L==0) = 0;
imshow
function.
imshow(img);
This should produce an image with the background removed and only the object of interest remaining. You may need to adjust the parameters of the grabcut
function and the initial mask to get the best results for your specific image.