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 Data Workflows에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!