Filter löschen
Filter löschen

problem with reading and writing image

1 Ansicht (letzte 30 Tage)
mohamad mohamad
mohamad mohamad am 15 Mär. 2014
Kommentiert: mohamad mohamad am 15 Mär. 2014
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),...

Akzeptierte Antwort

Azzi Abdelmalek
Azzi Abdelmalek am 15 Mär. 2014
Bearbeitet: Azzi Abdelmalek am 15 Mär. 2014
It's
imwrite (I, fileName, 'jpg');
or
imwrite (I, [fileName '.jpg']);
or
fileName = sprintf('C:\\result\\%02d.jpg',num);
imwrite (I, fileName);

Weitere Antworten (1)

Image Analyst
Image Analyst am 15 Mär. 2014
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.

Community Treasure Hunt

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

Start Hunting!

Translated by