Dynamic Variables in Loops
조회 수: 22(최근 30일)
I'm sure this has been answered before, but I can't seem to find the answer anywhere... Pretty simple problem for seasoned MATLAB users...
I have a series of images in a folder. I am trying to average these images. I start off by prompting the user for a folder to work from, then count the number of .jpg's in the folder. I run a loop to create a variable A for each image in the folder (A1, A2, A3, ....., A(i))
Now I need to assign those images to A(i) for them to processed.
Here is the code, thanks in advance. It is NOT recognizing A(i) (I think) and the error message is
Error in Average_Code (line 21) A(i)=imread(Files(i).name);
%User selecting image directory
%Counting number of .JPG's in folder
Files = dir('*.jpg')
%Create Dynamic Variables
eval(['A' num2str(i) '= i']);
fusion = 0;
%Assign Images to Dynamic Variables
fusion = fusion + A(i);
average_image = fusion/b;
Matt Tearle 2014년 10월 27일
편집: Matt Tearle 2014년 10월 28일
Yes, this has been answered before, and the answer is: generally, don't!
The specific problem you're having is that you created a bunch of variables called A1, A2, etc., but in the loop you're trying to reference A(2), which is not the same thing as A2.
You could keep everything in a single array A. How you do that depends on the files. If they are all B&W images of the same size, you could keep them in a 3-D double array:
A(:,:,i) = double(imread...);
Then, at the end,
average_image = mean(A,3);
Given that you're trying to do averaging, I assume your images are at least the same size. If they're color images, things get a bit gnarlier, but you could still do it with 4-D arrays (depending on what you mean by averaging the images).
EDIT TO ADD: OK, given your comment, if you're dealing with true-color images, imread will return them as 3-D arrays (m-by-n-by-3), so you could store the b different images in a 4-D array (m-by-n-by-3-by-b):
for i = 1:b
A(:,:,:,i) = double(imread(...));
If the "average" image is just the mean of each of the 3 color planes individually, then you can do
average_image = mean(A,4);
If you want something more complicated than that, then... well, I'm sure it's possible, but I don't know what it would look like.