How to Remove Image Background using Matlab?

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:

  1. Load the image into Matlab using the imread function.

 

img = imread('image.jpg');
  1. Create a mask that defines the region of the image you want to keep. This can be done manually using the 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;
  1. Run the 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);
  1. Apply the segmentation to the original image by setting the background pixels to 0 and the foreground pixels to their original values.

 

img(L==0) = 0;
  1. Display the resulting image using the 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.

Submit Your Programming Assignment Details