problem with reading and writing image
1 次查看(过去 30 天)
显示 更早的评论
NumberOfimages=4; %chose the number of images you want to give input
prefix_image='data ('; %change the desired input image name here only
fileformat=').tif'; %change the desired input image format here only
for num=1:NumberOfimages
I = imread(strcat(prefix_image,num2str(num),fileformat));
fileName = sprintf('C:\\result\\%02d',num);
imwrite (I, 'fileName', 'jpg');
end
i tried this code in order to read and save images,although the reading part worked well,the saving part doesn't work,can any one plz help me? my images are: data (1),data (2),...
0 个评论
采纳的回答
Azzi Abdelmalek
2014-3-15
编辑:Azzi Abdelmalek
2014-3-15
It's
imwrite (I, fileName, 'jpg');
or
imwrite (I, [fileName '.jpg']);
or
fileName = sprintf('C:\\result\\%02d.jpg',num);
imwrite (I, fileName);
更多回答(1 个)
Image Analyst
2014-3-15
You don't need to include the 'jpg' argument to imwrite. And you could make this code more robust. Try it like this:
folder = 'c:/result'; % Forward slashes work just fine with Windows.
if exist(folder, 'dir')
mkdir(folder);
end
% Loop over 4 images.
numberOfImages = 4; % choose the number of images you want to give input
for num = 1 : numberOfImage
% Read in input tif file.
inputFileName = sprintf('data (%d).tif', num);
fullInputFileName = fullfile(folder, inputFileName);
if ~exist(inputFileName, 'file')
continue; % Skip it not there.
end
I = imread(fullInputFileName);
% Write array to output file as a JPG format.
outputFileName = sprintf('data (%d).jpg', num);
% Could also have used outputFileName = strrep(inputFileName, '.tif', 'jpg');
fullOutputFileName = fullfile(folder, outputFileName);
imwrite (I, fullOutputFileName);
end
For even more robustness, try putting the code into a try/catch where you can put up an error message when something happens, and maybe even try to fix it and continue on
try
% Some code that might generate an error.
catch ME
errorMessage = sprintf('Error in function %s() at line %d.\n\nError Message:\n%s', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end
In my job it's essential to write robust code. If I didn't, I probably would have been fired by now.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Image Processing Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!