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)

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!