Hunter McMillen
Hunter McMillen

Reputation: 61512

Error writing image to file in Matlab

I am trying to write an image that I do operations on to a '.tif' file in a directory. I make the results directory with Matlab using the mkdir() function.

Here is the command I am using:

[pathstr, nameWOext, ext] = fileparts(filename);
results_dir = ['results' '/results_' nameWOext];

%check to see if the directory exists already, if it doesn't make it
if(exist(results_dir) ~= 7)
    mkdir(results_dir);
end

filenamezero = [nameWOext '_J' ext];

imwrite (~J, fullfile(results_dir, filenamezero));  //Error here

When Matlab gets to this line it outputs an error:

Could not open file for writing. Check directory or file permissions.

I inspected the folder 'results/results_' and the folder is read-only. Apparently mkdir() is doing this automatically.

Is there anyway to get around this?

Thanks

P.S. I am running Windows 7 using Matlab 6.1

Upvotes: 2

Views: 1402

Answers (2)

Doombot
Doombot

Reputation: 573

It seems that Matlab, when using an absolute path, requires to use ' / ' instead of the ' \ '.

For example, this works for me (Windows 8.1, Matlab R2012b)

imwrite(imagename, 'C:/Users/Myworkingfolder/myimage1.jpg','jpg'); 

But not:

imwrite(imagename, 'C:\Users\Myworkingfolder.jpg','jpg'); 

And this, even if Windows itself uses the ' \ ' when you copy a path from Windows explorer.

Although, when using a relative path, such as writing in the current folder in Matlab:

imwrite(imagename, 'Myworkingfolder/myimage1.jpg','jpg'); 

and

imwrite(imagename, 'Myworkingfolder\myimage1.jpg','jpg'); 

It works out of the box. It might be with how both cases (absolute and relative paths) are implemented...

Upvotes: 0

aganders3
aganders3

Reputation: 5945

I think your problem may be your use of the fullfile function. I think the result is that the path you are trying to pass to imwrite has a mix of \ and / for file separators.

Try using this instead:

filenamezero = [nameWOext '_J' ext];
imwrite (~J, [results_dir '/' filenamezero]);

Upvotes: 4

Related Questions