Hello everyone, I would like to ask you that how to write code to remove the background of the picture.Thanks a lot.
Show older comments
Answers (2)
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;
%--------------------------------------------------------------------------------------------------------
% READ IN IMAGE
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);
end
%--------------------------------------------------------------------------------------------------------
% Display the image.
subplot(2, 2, 1);
imshow(grayImage, []);
axis('on', 'image');
title('Gray Scale Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
hFig = gcf;
hFig.WindowState = 'maximized'; % May not work in earlier versions of MATLAB.
drawnow;
% 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');
impixelinfo;
% Show the histogram
subplot(2, 2, 3);
histogram(sdImage);
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');
impixelinfo;
drawnow;

Wesley
on 23 May 2021
0 votes
1 Comment
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.
Categories
Find more on Convert Image Type in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!