How can I automatically do thresholding multiple images in a folder by for loop?

5 次查看(过去 30 天)
Hello everyone. I have 100 images in a folder. I intend to read all the images and threshold it in order to count the black pixels in my image. The problem is that I can only do it for one image and not for all of them. Below is the code that I used for only one image. Any help would be appreciated.
clear all;close all;clc;
A=imread('1.png');
[X,map]=imread('1.png');
A=imresize(A,1);
figure
imshow(A)
figure
A=rgb2gray(A);
A=medfilt2(A,[1,1]);
level = graythresh(A);
BW = im2bw(X,map,0.45);
imshow(BW)
blackpixels_eachtime=sum(BW(:)==0)
Total_black_pixels=648282;
RF=((Total_black_pixels-blackpixels_eachtime)/(Total_black_pixels))*100

采纳的回答

Image Analyst
Image Analyst 2020-5-25
  3 个评论
Image Analyst
Image Analyst 2020-5-25
You should not have that inner loop. I made a lot of other fixes, and here is the repaired code:
clc; % Clear the command window.
fprintf('Beginning to run %s.m.\n', mfilename);
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 = 15;
imageList = dir('*.png');
numberOfImages = length(imageList);
for k = 1 : numberOfImages
fullfileName= fullfile(imageList(k).folder, imageList(k).name);
rgbImage = imread(fullfileName);
% Optional display of the image.
imshow(rgbImage);
title(imageList(k).name, 'FontSize', fontSize, 'Interpreter', 'none');
drawnow;
[rows, columns, numberOfColorChannels] = size(rgbImage);
if numberOfColorChannels == 3
% Convert to gray scale.
grayScaleImg = rgb2gray(rgbImage);
else
% It's already gray scale.
grayScaleImg = rgbImage;
end
grayScaleImg = im2bw(grayScaleImg, 0.54);
[~,baseFileNameNoExt,~] = fileparts(fullfileName);
gsFilename=sprintf('%s_gs.png', baseFileNameNoExt);
% imwrite(grayScaleImg, gsFilename);
blackPixels(k) = sum(grayScaleImg(:)==0);
end
bar(blackPixels, 1);
caption = sprintf('Number of black pixels for %d images', numberOfImages);
title(caption, 'FontSize', fontSize, 'Interpreter', 'none');
xlabel('Image Number', 'FontSize', fontSize);
ylabel('Number of Black Pixels', 'FontSize', fontSize);
grid on;
g = gcf;
g.WindowState = 'maximized'
fprintf('Done running %s.m.\n', mfilename);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Image Processing Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by