How do I remove the white background of any image?

조회 수: 17 (최근 30일)
Rosy
Rosy 2018년 2월 17일
댓글: Walter Roberson 2020년 4월 10일
I want to remove white backgrounds of the image and crop only the currency image portion.
  댓글 수: 4
Image Analyst
Image Analyst 2018년 2월 17일
Easy, but why? How is your algorithm harmed by the white frame?
Rosy
Rosy 2018년 2월 17일
Thanks. When I am trying to calculate height width ratio of the currency it gives a inaccurate calculation.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2018년 2월 17일
See attached.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = '200_bcg.jpg';
folder = pwd
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
%=======================================================================================
% Read in demo image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis on;
caption = sprintf('Original Color Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
[mask, maskedRGBImage] = createMask(rgbImage);
% Take the largest blob only, to get rid of noise.
% mask = bwareafilt(mask, 1);
% Fill any holes in it.
mask = imfill(mask, 'holes');
% Let's assume it's supposed to be convex. Make sure.
mask = bwconvhull(mask);
% Display the image.
subplot(2, 2, 2);
imshow(mask, []);
axis on;
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Mask the image with the new, cleaned mask.
% Mask the image using bsxfun() function to multiply the mask by each channel individually.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
% Display the image.
subplot(2, 2, 3);
imshow(maskedRgbImage, []);
axis on;
title('Masked RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Get the equivalent bounding box.
props = regionprops(mask, 'BoundingBox');
% Crop the image
croppedImage = imcrop(rgbImage, props.BoundingBox);
% Display the image.
subplot(2, 2, 4);
imshow(croppedImage, []);
axis on;
title('Cropped RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
function [BW,maskedRGBImage] = createMask(RGB)
%createMask Threshold RGB image using auto-generated code from colorThresholder app.
% [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
% auto-generated code from the colorThresholder app. The colorspace and
% range for each channel of the colorspace were set within the app. The
% segmentation mask is returned in BW, and a composite of the mask and
% original RGB images is returned in maskedRGBImage.
% Auto-generated by colorThresholder app on 17-Feb-2018
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.000;
channel1Max = 1.000;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.077;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.000;
channel3Max = 1.000;
% Create mask based on chosen histogram thresholds
sliderBW = (I(:,:,1) >= channel1Min ) & (I(:,:,1) <= channel1Max) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
% Initialize output masked image based on input image.
maskedRGBImage = RGB;
% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;
end
  댓글 수: 4
Rosy
Rosy 2018년 2월 17일
편집: Rosy 2018년 2월 17일
No it was before with the white bcg. Now its fine. Thanks for the solution. Its help me to crop only the actual currency image for further processing.
Rosy
Rosy 2018년 3월 21일
편집: Image Analyst 2018년 3월 21일
Previous answer helps me a lot . I need your help on this for further progress. Please check this one.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

mohd abdul wahed faisal faisal
mohd abdul wahed faisal faisal 2019년 7월 31일
편집: mohd abdul wahed faisal faisal 2019년 7월 31일
bro i want to remove outer white part(border) from image.while reading and showing it is happening like this.
  댓글 수: 3
Malini Bakthavatchalam
Malini Bakthavatchalam 2020년 4월 10일
Sir I have a question. I have a color image , so I have to use the alpha layer remove background and find the median of the image histogram and then break them into two halfs like below and above the median and get the three images including the original color image, upper and lower rectified image and their corresponding histograms? I am able to make the code in bits and pieces but not whole thing as a script .
Walter Roberson
Walter Roberson 2020년 4월 10일
What error do you encounter when you attempt to put the three parts together?
If you are able to get all three parts working separately, you could consider putting the parts into functions, so that the functions would not interfere with each other.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Image Segmentation and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by