Search code examples
matlabimread

Matlab - imread - the argument must be a string


I'm trying to run imread on all the images in a folder. I have accomplished this task, but there is an error which says that my argument is not a string.

h_path = 'C:\Users\john\Matlab\train';
dirlist = dir('*.jpg');

for i = 1:length(dirlist)
    f_path = strcat(h_path,{'\'},dirlist(i).name);
    disp(f_path);
    I = imread(f_path); 

The error happens on the last line. Also, the disp function prints out my path without any errors.


Solution

  • The problem of your code is the {'\'}, not sure why you put a cell array here in. Simply using a char and your code works:

    for i = 1:length(dirlist)
       f_path = strcat(h_path,'\',dirlist(i).name);
       disp(f_path);
       I = imread(f_path); 
    end
    

    As Oleg already mentioned, it is better practice to use fullfile, it's platform independent and avoids issues with duplicated file seperators.

    for i = 1:length(dirlist)
       f_path = fullfile(h_path,dirlist(i).name);
       disp(f_path);
       I = imread(f_path); 
    end