Need help incrementally nameing files as it saves in a loop
조회 수: 10 (최근 30일)
이전 댓글 표시
So let me premept this by saying I am in every single way an amateur with matlab. I am developing a code that will enable me to crop a series of images in a folder with a standardized crop size, then save the cropped images with a new name to a new folder. The entire code is working (albeit probably inefficient and poorly) aside from the renaming aspect of it.
%operating all pictures in a folder
clear all
close all
clc
dname_open = input('Please Enter the Directory Address of the Images:','s');
dname_save = input('Please Enter the Directory Address of the Save Destination:', 's');
%Code Test parameter (Will only do first image in folder if test=1)
test = 0;
%Set up basic file name path to be read
top_file = [dname_open '\'];
ls_top_file = ls(top_file);
c = cellstr(ls_top_file);
cc = c(3:length(c));
S = size(cc);
a = 1;
S(1)
%Input image for crop coordinates
close all
file = char(cellstr([top_file char(cc(a))]));
data_n = char(cc(a));
file_name = char(cc(a));
imagename = (file_name)
fileToRead2 = [dname_open '\' imagename];
I = imread(fileToRead2);
[I1c rect]= imcrop(I)
I2 = imcrop(I, rect);
imshow (I2, 'Border', 'Tight');
set(gcf, 'Position', [0 0 1 1]);
h = gcf;
saveas(h, [dname_save '\' 'IMG_' '001'], 'jpg')
%Crop Loop
while a<= S(1)
close all
file = char(cellstr([top_file char(cc(a))]));
data_n = char(cc(a));
file_name = char(cc(a));
% Operations on files
imagename = (file_name);
newname= sprintf('%d IMG_');
%Input image
fileToRead2 = [dname_open '\', imagename];
I = imread(fileToRead2);
%Cropping
%Vector [xmin, ymin, width, height]
I2 = imcrop(I, rect);
imshow(I2,'Border','Tight');
set(gcf, 'PaperPositionMode', 'auto');
h = gcf;
saveas(h, [dname_save '\' 'IMG_', a], 'jpg');
if test == 1
fprintf('breaking loop to set axis - test==1')
break
end
a=a+1
end
The error lies in "saveas(h, [dname_save '\' 'IMG_', a], 'jpg');" of this code. It won't work using "a" to increment the save name, but works fine when I use the variable "imagename"
Any help would be greatly appreciated.
댓글 수: 0
채택된 답변
Star Strider
2014년 10월 27일
I didn’t run your code so you have to do this experiment. See if:
saveas(h, [dname_save '\' 'IMG_', num2str(a,'%d')], 'jpg');
improves things.
댓글 수: 3
per isakson
2014년 10월 28일
An alternative
saveas( h, fullfile( dname_save, sprintf( 'IMG_%03d.jpg', a ) ) );
The format specifier,   %03d,   with leading zeros make the names easier to use in Windows Explorer.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!