How can I remove unwanted area by mask?

5 ビュー (過去 30 日間)
Jenifer NG
Jenifer NG 2022 年 7 月 4 日
コメント済み: DGM 2022 年 7 月 5 日
Dear All,
Could anyone help to remove unwanted area by using a mask? as figure bellow
  • I create a mask by thresholding
  • Then want to remove unwanted area by the mask
% here is my code
I = imread('coins.png');
X = imadjust(I);
% Threshold image - manual threshold
BW = im2gray(X) > 5.355000e+01;
% Dilate mask with default
radius = 1;
decomposition = 4;
se = strel('disk', radius, decomposition);
BW = imdilate(BW, se);
% Create masked image.
maskedImage = X;
maskedImage(~BW) = 0;
imwrite(maskedImage,'mask.png')
  3 件のコメント
Jenifer NG
Jenifer NG 2022 年 7 月 4 日
thanks you my simple mistake :((
Jenifer NG
Jenifer NG 2022 年 7 月 4 日
How can I put process for multiple image ?

サインインしてコメントする。

採用された回答

DGM
DGM 2022 年 7 月 4 日
編集済み: DGM 2022 年 7 月 5 日
Just get the file names somehow and read/process/write the files in a loop.
This is one example based on simple pattern matching.
% you'll have to set these directories
inFolder = 'sources'; % this is just where i had some test files
outFolder = './'; % the folder to place the outputs in
outfiletype = '.png'; % this makes it easy to change
filePattern = fullfile(inFolder, '*.jpg'); % select which files to load
allFiles = dir(filePattern);
for k = 1:length(allFiles)
baseFileName = allFiles(k).name;
fullFileName = fullfile(inFolder, baseFileName);
% process image...
I = imread(fullFileName);
I = im2gray(I); % image needs to be gray if using imadjust() like that
I = imadjust(I);
% Threshold image - manual threshold
% you'll have to come up with a way to do the thresholding
% that's effective for all images. that's not something i can guess
BW = I > 5.355000e+01;
% Dilate mask with default
radius = 1;
decomposition = 4;
se = strel('disk', radius, decomposition);
BW = imdilate(BW, se);
% Create masked image.
maskedImage = I;
maskedImage(~BW) = 0;
% write images
% this assumes all input images are .jpg or .png; add cases as needed
fnamenoext = regexprep(baseFileName,'(.jpg$)|(.png$)','');
% build filename out of old filename, k, and specified path/extension
FileName = fullfile(outFolder,sprintf('%s_masked%s',fnamenoext,outfiletype))
imwrite(maskedImage,FileName); %B is the output images
end
See also:
  5 件のコメント
Image Analyst
Image Analyst 2022 年 7 月 5 日
BW = bwareafilt(BW, 1); % Keep largest blob only.
DGM
DGM 2022 年 7 月 5 日
Oh sorry. I meant to delete that. You should be able to use the im2gray() line that's commented out.
I used mono() since I'm using an older version that doesn't have im2gray().

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 7 月 4 日
"How can I put process for multiple image ? " << See the FAQ:

カテゴリ

Help Center および File ExchangeImage Processing Toolbox についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by