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

5 views (last 30 days)
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

Accepted Answer

Image Analyst
Image Analyst on 25 May 2020
  3 Comments
Image Analyst
Image Analyst on 25 May 2020
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);

Sign in to comment.

More Answers (0)

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!