Matlab:将图像序列写入文件夹

时间:2013-06-06 12:45:10

标签: image matlab file-io

我正在尝试使用Matlab中的imwrite函数将一系列图像写入文件夹。我首先使用给定矩阵裁剪输入图像(inputImgcropMatrix,然后将这些结果图像保存到文件夹中。我的代码如下:

for i = 1:n
    img = imcrop(inputImg,cropMatrix);
    fileName = sprintf('C:\Users\King_Knight\Desktop\Images\%02d',i);
    imwrite ( img, 'fileName', 'jpg');
end

然后文件夹完全是空的,它没有写出任何东西,除了我在Matlab工作区中收到一条警告信息:

Warning: Escape sequence '\U' is not valid. See 'help sprintf' for valid escape sequences.

我搜索过互联网,但仍无法解决。有人可以帮忙吗?谢谢。

3 个答案:

答案 0 :(得分:2)

Matlab中的*printf函数集将解释C风格的转义码,它始终以字符\开头。一个常见的问题当然是Windows使用反斜杠作为目录分隔符。

简单的解决方案是使用\\转义所有反斜杠。例如:

fileName = sprintf('C:\\Users\\King_Knight\\Desktop\\Images\\%02d',i);

实际上会根据需要创建字符串C:\Users\King_Knight\Desktop\Images\00

您可以阅读相关文档here

请注意,在Matlab中,与C不同,这仅适用于fprintfsprintf等函数。必须为其他函数执行此操作,例如: disp

答案 1 :(得分:1)

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

%%

答案 2 :(得分:0)

如果要将图像写入目标文件夹,请在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.

我希望这个答案对某些人有所帮助。

相关问题