Reputation: 3582
I am trying to write a sequence of images into a folder using imwrite
function in Matlab. I first crop the input image (inputImg
) with a given matrix as cropMatrix
, then save those resulted images in order to a folder. My code for it is as follows:
for i = 1:n
img = imcrop(inputImg,cropMatrix);
fileName = sprintf('C:\Users\King_Knight\Desktop\Images\%02d',i);
imwrite ( img, 'fileName', 'jpg');
end
Then the folder is totally empty, it didn't write out anything, besides I got a warning message in the Matlab workspace saying:
Warning: Escape sequence '\U' is not valid. See 'help sprintf' for valid escape sequences.
I've searched the internet, but still couldn't solve it. Could someone help? Thanks.
Upvotes: 0
Views: 4212
Reputation: 11
If you want to write the image into destination folder use the following code in MATLAB.
destinationFolder = 'C:\Users\Deepa\Desktop\imagefolder'; % Your folder path
if ~exist(destinationFolder, 'dir')
mkdir(destinationFolder);
end
baseFileName = sprintf('%d.png', i); % e.g. "1.png"
fullFileName = fullfile(destinationFolder, baseFileName);
imwrite(img, fullFileName); % img respresents input image.
I hope this answer might help someone.
Upvotes: 0
Reputation: 11
clear all;
%%%% Image Read
%%
input_folder = '..'; % Enter name of folder from which you want to upload pictures with full path
output_folder = '..';
filenames = dir(fullfile(input_folder, '*.jpg')); % read all images with specified extention, its jpg in our case
total_images = numel(filenames); % count total number of photos present in that folder
Outputs=total_images;
dir=output_folder;
%%
%%
for i = 1:total_images
full_name= fullfile(input_folder, filenames(i).name); % it will specify images names with full path and extension
our_images = imread(full_name); % Read images
figure (i); % used tat index n so old figures are not over written by new new figures
imshow(our_images); % Show all images
I = our_images;
I = imresize(I, [384 384]);
filename = [sprintf('%03d',i) '.jpg'];
fullname = fullfile(output_folder,'output_folder',filename);
imwrite(I,fullname) % Write out to a JPEG file (img1.jpg, img2.jpg, etc.)
end
%%
Upvotes: 1
Reputation: 7213
The *printf
set of functions in Matlab will interpret C-style escape codes, which always start with the character \
. A common problem is of course that Windows uses the backslash as a directory separator.
The simple solution is the escape all of the backslashes using \\
. For example:
fileName = sprintf('C:\\Users\\King_Knight\\Desktop\\Images\\%02d',i);
will actually create the string C:\Users\King_Knight\Desktop\Images\00
, as required.
You can read the relevant documentation here.
Note that in Matlab, unlike C, this only applies to the functions fprintf
, sprintf
etc. You don't have to do it for other functions such as disp
.
Upvotes: 2