How to add loop for saving multiple images into a specific folder?
9 views (last 30 days)
Show older comments
Hi. I've run this code. No error occur, but it save only the last cropped image in bounding box while the other cropped images are not. Fyi, in my case, an image of bounding box will produce few cropped images which I named it as 'obj'. Meanwhile 'I12' is the resize of the cropped image. Thus, where should I add the looping and what are the codes should I write for the loop? Please help me. Thanks in advance.
srcFile=dir('C:\Users\User\Documents\FYP\Matlab\cnPVG\*.bmp');
for ck=1:length(srcFile)
filenamecn=strcat('C:\Users\User\Documents\FYP\Matlab\cnPVG\',srcFile(ck).name);
img_src =imread(filenamecn);
.
.
.
.
.
.
% Bounding box
imbwlabel=bwlabel(I8); %bwlabel works only in binary (b&w,double) image
% figure;
% % imshow(label2rgb(imbwlabel)); %this is important bcs it helps to create the bounding box
% %in colored (uint8,unit16 etc) image and not in binary (b&w) image
%
bboxes=regionprops(imbwlabel,'BoundingBox');
[L, n]=bwlabel(I8);
bboxes=regionprops(I8,'BoundingBox','Centroid');
%
% figure;imshow(I10);%title('Image with Bounding box');
axis image off
hold on
for k=1 : length(bboxes)
CurrBB=bboxes(k).BoundingBox;
% cent=cat(1,bboxes.BoundingBox);
% plot(cent(:,1),cent(:,2),'g*')
rectangle('Position', [CurrBB(1),CurrBB(2),CurrBB(3),CurrBB(4)], 'EdgeColor','m','LineWidth',2)
end
hold off
%%crop and zero padding
if ~isempty(bboxes)
for p=1:length(bboxes)
CurrBB=bboxes(p).BoundingBox;
obj = imcrop(I10,CurrBB);
[m, n, l]=size(obj);
if (m > 227 || n > 227)
obj=imresize(obj,[227 227]);
end
I12=zeros(227,227);
I12=uint8(I12);
for i=1:m
for j=1:n
for t=1:3
if (m > 227 || n > 227)
obj=imresize(obj,[227 227]);
else I12(i,j,t)=obj(i,j,t);
end
end
end
end
path=strcat('C:\Users\User\Documents\FYP\Matlab\bbbPVG\',srcFile(ck).name);
imwrite(I12,path);
end
% figure;imshow(I12);
% figure;imshow(obj);
end
end
8 Comments
Answers (1)
Image Analyst
on 12 Jun 2022
Try
props = regionprops(I8, 'BoundingBox', 'Centroid');
% Extract from structure into more convenient 2-D matrices.
allXyCentroids = vertcat(props.Centroid) % N-by-2 list of all (x,y) centroid coordinates.
allBBs = vertcat(props.BoundingBox) % N-by-4 matrix of all bounding boxes. Each row is one box.
3 Comments
Image Analyst
on 13 Jun 2022
I think you didn't see the comment on the last line:
% N-by-4 matrix of all bounding boxes. Each row is one box.
So it's an N row matrix where there is one row for every one of the N boxes. The first column is the xLeft coordinate. The second column is the yTop row of the blobs. The third column is the widths of the boxes (in columns of pixels from center to center), and the fourth column is the height of the boxes (in rows or lines of pixels).
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!