getting absurd result in For loop

6 ビュー (過去 30 日間)
NAVNEET NAYAN
NAVNEET NAYAN 2017 年 3 月 31 日
コメント済み: NAVNEET NAYAN 2017 年 3 月 31 日
multi = dir('D:\testing\abrupt\*.jpg');
for i = 1:2:length(multi)
filename = strcat('D:\testing\abrupt\',num2str(i),'.jpg');
I = imread(filename);
I1 = rgb2gray(I);
mat1(:,:,i)= I1;
end
In the folder "multi" images are saved as 1.jpg 3.jpg 5.jpg...etc.the total number of images in "multi"was 133 and it is like 1,3,5,7....265, means only odd number of images are saved. when this code was run, the I am getting m-by-n-by-133 mat1(:,:,i) values but problem encountered is that mat1(:,:,2), mat1(:,:,4), mat1(:,:,6) or mat1(:,:,even no.) are having all matrix elements as zero whereas mat1(:,:,odd number) are giving correct result? How can I solve this problem??

採用された回答

Jan
Jan 2017 年 3 月 31 日
編集済み: Jan 2017 年 3 月 31 日
The results is not absurd, but exactly as expected. Try this:
a = [];
a(1) = 1;
a(3) = 3;
disp(a)
The element a(2) is filled by a 0 implicitly. There are no "gaps" in numerical arrays. Solution:
FileList = dir('D:\testing\abrupt\*.jpg');
for iFile = 1:length(FileList)
filename = fullfile('D:\testing\abrupt\', FileList(iFile));
I = imread(filename);
I1 = rgb2gray(I);
mat1(:, :, iFile)= I1;
end
If you want to exclude the files with the even indices:
FileList = dir('D:\testing\abrupt\*.jpg');
index = 0;
for iFile = 1:2:length(FileList)
filename = fullfile('D:\testing\abrupt\', sprintf('%d.jpg', iFile));
I = imread(filename);
I1 = rgb2gray(I);
index = index + 1;
mat1(:,:, index) = I1;
end
  1 件のコメント
NAVNEET NAYAN
NAVNEET NAYAN 2017 年 3 月 31 日
Thanks Simon, It's working now...

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

その他の回答 (1 件)

KSSV
KSSV 2017 年 3 月 31 日
編集済み: KSSV 2017 年 3 月 31 日
In the for loop you are taking only even numbers....change it to 1:1:length(multi)
multi = dir('D:\testing\abrupt\*.jpg');
for i = 1:1:length(multi)
filename = strcat('D:\testing\abrupt\',num2str(i),'.jpg');
I = imread(filename);
I1 = rgb2gray(I);
mat1(:,:,i)= I1;
end
  1 件のコメント
NAVNEET NAYAN
NAVNEET NAYAN 2017 年 3 月 31 日
when i am doing for i = 1:1:length(multi) i am getting an error : File "D:\testing\abrupt\2.jpg" does not exist. Error in program_number_2(line 7) I2 = imread(filename);

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

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by