imwrite does not work when file extension is given

I am trying to create a folder of images using imwrite in a for loop. All previous problems with imwrite seem to stem from a permission problem or incorrect file naming. I have ensured my file permissions are correct in windows and I cannot find any error in my file naming. I first create a folder path using mkdir. Then, within a loop I define my image and its name, then save it using imwrite. Within imwrite I use fullfile(path,name) to create a correct file name at the location I want.
Here is my simple code
%% Greyscale shrinkage control structures
gval = 0.5;
grey = repelem(gval,95);
grey = uint8(grey*255);
wc = 608/2;
hc = 684/2;
w = 100;
h = 200;
path = fullfile(pwd,'grey_beams',['grey_shrinkage_control_' 'grey_val_' strrep(num2str(gval),'.','-')]);
mkdir(path)
for i = 1:96
I = uint8(zeros(684,608));
if i > 3 && i < 96
I(hc-h:hc+h,wc:wc+w) = 255;
I(hc-h:hc+h,wc-w:wc-1) = grey(i);
elseif i <= 3
I(hc-h:hc+h,wc-250:wc+250) = 255;
end
name = ['pattern_' sprintf('%03d',i-1) '.bmp']
imwrite(I,fullfile(path,name),'bmp')
end
This gives me the following error for the first iteration of the loop
% Error using imwrite (line 548)
% Unable to open file "C:\Users\Jason Johnson\Documents\Purdue\Purdue_Research\Polymerization
% Model\Code\Spatiotemporal Code\grey_beams\grey_shrinkage_control_grey_val_0-5\pattern_000.bmp" for
% writing. You might not have write permission.
%
% Error in grey_shrinkage_tuning (line 26)
% imwrite(I,fullfile(path,name),'bmp')
This code works perfectly when I delete '.bmp' from name on line 25. But, then it saves the files with no particular format, when, instead, I need them to be a bitmap.
Furthermore, the given code will work if I insert
edit(fullfile(path,name))
before the imwrite on line 26. However, then the code is slowed down significantly, and I have 96 tabs in the editor window that I have to close manually.
What is causing this file permission error?

5 Comments

You have opened a file of that name previously and not closed it would be my hypothesis...ensure the target directory is empty first and you haven't any open in some other application.
dpb,
I have added the following lines of code to my script and I still have the same issue.
if exist(path,'dir')
rmdir(path)
end
Seems you have already had the files with same file names in the directory and they are set to read only.
Simon,
I have checked to make sure the files do not exist. I tried this code to ensure the file does not exist prior to using imwrite,
if exist(fullfile(path,name))
delete(fullfile(path,name))
end
This did not make a difference. I also tried using fopen with 'w' permission to create a file in case imwrite was having trouble creating the file for some reason. When I did this I just got a permission denied response from fopen. Then if I go back and check if the file exists it still does not. I am on a personal computer where all users have administrative access.
dpb
dpb on 13 Jul 2021
Edited: dpb on 13 Jul 2021
The deal about only the extension being on the filename causing the problem convinces me it is something of the sort if you can otherwise access the subdirectory.
It isn't imwrite that's the culprit if fopen() also has the problem--that's tied in to the OS and file system and permissions for the specific file(s).

Sign in to comment.

 Accepted Answer

Jan
Jan on 13 Jul 2021
Edited: Jan on 13 Jul 2021
Do not use "path" as name of a variable, because this shadows an important Matlab command. This does run usually, but during debugging you can get serious troubles.
Relying on this current directory is fragile, because any callback of a timer or GUI can change it unexpectedly. So instead of useing pwd() (which does nothing than callin cd() by the way), provide an absolute path.
"then it saves the files with no particular format" - there are no files without a format. imwrite uses the format from the file name, if you omit the specifier 'bmp' to determine the format.
Use this code for checking the existence of the file:
gval = 0.5;
grey = repmat(uint8(gval * 255), 1, 95);
wc = 608/2;
hc = 684/2;
w = 100;
h = 200;
base = 'C:\Your\Base\Path';
folder = fullfile(base, 'grey_beams', ...
['grey_shrinkage_control_grey_val_', strrep(num2str(gval), '.', '-')]);
mkdir(folder)
for i = 1:96
I = zeros(684,608, 'uint8');
if i <= 3
I(hc-h:hc+h, wc-250:wc+250) = 255;
elseif i < 96
I(hc-h:hc+h, wc:wc+w) = 255;
I(hc-h:hc+h, wc-w:wc-1) = grey(i);
end
file = fullfile(folder, sprintf('pattern_%03d.bmp', i-1));
if isfile(file)
error('File is existing already: %s', file);
end
imwrite(I, file, 'bmp');
% ^^^^^ this is optional
end
What do you observe?
I've inserted some simplifications in the code.

8 Comments

Jan,
Thank you for the correction on my definition of my file directory I have updated it accordingly. I copy and pasted your code and updated the base filepath and I received the same error. I have tried my original code and your code on another computer and they worked perfectly. This leads me to believe its an issue or bug specific to my computer.
What if you change the base directory?
I do have some concern about the length of the file name, which is over 160. However, provided that you are using NTFS file system (not saving to a thumb drive, not using a network drive) then that length should be okay, as the maximum length is 260 (including drive)
Interesting thought there, Walter.
Although his error message shows the fully-qualified file name begins with 'C:\Users..." so is on the local machine drive so the periperals/network drive, etc., should not be an issue, makes one wonder what might happen if OP were to shorten the file name by the length of the extension keeping the overall length the same (or shorter). Would the symptoms change? The MS file system docs would suggest not, but would be most enlightening if did that mayhaps he's somehow got embedded nonprinting characters in the name or the like that we can't see...
It seems bizarre on the surface; difficulty in trying to debug stuff like this remotely without actual access to the machine...
Walter and dbp,
I have tried numerous different and shorter file names and locations to no avail. This problem seems to occur regardless of my file name or type. Both fopen and imwrite work fine until I add any type of file extension to the name. This issue did not happen with MATLAB 2017 using very similar code. I am running out of ideas short of re-installing MATLAB.
As far as I understand:
fopen(fullfile(tempdir, 'test'), 'w') % working, replies fid >= 3
fopen(fullfile(tempdir, 'test.bmp'), 'w') % failing, replies fid == -1
Is this correct?
Does your antivirus software protect the folder?
That is correct. Pausing my antivirus software solves the issue!
For some reason my antivirus software had decided to designate MATLAB as a shady app. Removing this designation has solved my issue. Thank you Jan for leading me to this issue!

Sign in to comment.

More Answers (2)

I ran the original code and it ran fine - no errors. Nonetheless, I made some improvements in it:
fprintf('Beginning to run %s.m ...\n', mfilename);
%% Greyscale shrinkage control structures
gval = 0.5;
grey = repelem(gval,95);
grey = uint8(grey*255);
wc = 608/2;
hc = 684/2;
w = 100;
h = 200;
folder = fullfile(pwd,'grey_beams', ['grey_shrinkage_control_', 'grey_val_', strrep(num2str(gval),'.','-')]);
if ~isfolder(folder)
mkdir(folder);
end
for k = 1 : 96
grayImage = uint8(zeros(684,608));
if k > 3 && k < 96
grayImage(hc-h:hc+h,wc:wc+w) = 255;
grayImage(hc-h:hc+h,wc-w:wc-1) = grey(k);
elseif k <= 3
grayImage(hc-h:hc+h,wc-250:wc+250) = 255;
end
baseFileName = sprintf('pattern_%03d.bmp', k-1);
fullFileName = fullfile(folder, baseFileName);
fprintf('Writing %s\n', fullFileName);
imwrite(grayImage, fullFileName);
end
fprintf('Done running %s.m.\n', mfilename);
What if you try using PNG images? PNG is a much more common format these days than BMP.

1 Comment

Image Analyst,
Thank you for improving my code. My use for these images requires a BMP format. But regardless, changing the format does not seem to solve the issue. Unfortunately, it seems to be specfic to my machine.

Sign in to comment.

The code presented in the original question works well on other machines. Additionally, changing the file name and location seems to have no effect on the issue. Both fopen and imwrite are unable to write to a file anytime a file extension is included in the name.
Does anyone have any ideas on doing some debugging more specific to file management on my machine, whether that be through MATLAB or Windows?

Categories

Find more on Convert Image Type in Help Center and File Exchange

Products

Release

R2020b

Asked:

on 13 Jul 2021

Commented:

on 14 Jul 2021

Community Treasure Hunt

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

Start Hunting!