Clear Filters
Clear Filters

Hello everyone, I would like to ask you that how to write code to remove the background of the picture.Thanks a lot.

3 views (last 30 days)
Wesley on 21 May 2021
% Demo to have the user freehand draw an irregular shape over a gray scale image.
% Then it creates new images:
% (1) where the drawn region is untouched inside the region and all black outside the region.
clc; % Clear command window.
% clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 16;
% Read in a standard MATLAB gray scale demo image.
folder = pwd; % Determine where demo folder is.
baseFileName = 'imgsp1466.jpg';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
grayImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(grayImage);
imshow(grayImage, []);
axis on;
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% Ask user to draw freehand mask.
message = sprintf('Left click and hold to begin drawing.\nSimply lift the mouse button to finish');
hFH = imfreehand(); % Actual line of code to do the drawing.
% Create a binary image ("mask") from the ROI object.
binaryImage = hFH.createMask();
xy = hFH.getPosition;
% Now make it smaller so we can show more images.
subplot(3, 1, 1);
imshow(grayImage, []);
axis on;
title('Original gray scale image', 'FontSize', fontSize);
% Display the freehand mask.
subplot(3, 1, 2);
axis on;
title('Binary mask of the region', 'FontSize', fontSize);
% Calculate the area, in pixels, that they drew.
numberOfPixels1 = sum(binaryImage(:))
% Another way to calculate it that takes fractional pixels into account.
numberOfPixels2 = bwarea(binaryImage)
% Mask the image outside the mask (make it black outside the white mask region), and display it.
% Will keep only the part of the image that's inside the mask, zero outside mask.
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
blackMaskedImage = bsxfun(@times, grayImage, cast(binaryImage, 'like', grayImage));
subplot(3, 1, 3);
axis on;
title('Masked black outside region', 'FontSize', fontSize);

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 21 May 2021
Edited: Image Analyst on 21 May 2021
Try to find smooth and rough parts using stdfilt(). Then threshold and call regionprops. Something like
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
folder = pwd;
baseFileName = 'image.png';
grayImage = imread(baseFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(grayImage)
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
grayImage = min(grayImage, [], 3);
% Display the image.
subplot(2, 2, 1);
imshow(grayImage, []);
axis('on', 'image');
title('Gray Scale Image', 'FontSize', fontSize, 'Interpreter', 'None');
hFig = gcf;
hFig.WindowState = 'maximized'; % May not work in earlier versions of MATLAB.
% Filter the image with a moving standard deviation filter.
sdImage = stdfilt(grayImage, ones(21, 21));
subplot(2, 2, 2);
imshow(sdImage, []);
axis('on', 'image');
title('Standard Deviation Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Show the histogram
subplot(2, 2, 3);
title('Histogram of Standard Deviation Image', 'FontSize', fontSize, 'Interpreter', 'None');
grid on;
% Turn into a binary image
threshold = 7;
xline(threshold, 'color', 'r', 'LineWidth', 3); % Show threshold over histogram.
binaryImage = sdImage > threshold;
% Get rid of blobs touching border.
binaryImage = imclearborder(binaryImage);
% Fill holes
binaryImage = imfill(binaryImage, 'holes');
% Display the image.
subplot(2, 2, 4);
imshow(binaryImage, []);
axis('on', 'image');
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');

Wesley on 23 May 2021
Thank you very much for answering my question. Compared with the original image, the difference between the image extracted by this method and the original image is relatively large, and the error of the later morphological analysis is large. I wonder if I can use other methods to extract the original appearance of the small sand pile as much as possible.
  1 Comment
Image Analyst
Image Analyst on 23 May 2021
Of course. feel free to experiment around with the parameters like the standard deviation window size, intensity threshold, area range to accept segmented blobs. There are lots of things you can play around with, so have at it.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!