Read, Crop and then Save multiple images

I am really new to Matlab, but I need for a project to crop multiple images with the same rectangle and then save them into a new folder.
(I have 172 images in the folder, first one is called frame10.jpg, last one is frame182.jpg)
Here's my code so far:
for n=10:182
image_{n}=imread(sprintf('frame%s.jpg', num2str(n)));
end
[x rect] = imcrop(image_{10})
for n=11:182
imcrop(image_{n}, rect)
end
When I Run it, it opens up all the figures of the images correctly cropped.
My questions are: how can I tell matlab not to open up all the figures of the cropped images since I do not need to see them?
How do I save all the cropped images in a new folder 'Cropped' inside the current folder? (possibly using imwrite but it's not necessary)

 Accepted Answer

KSSV
KSSV on 12 Apr 2018
Edited: KSSV on 14 Apr 2018
images = dir('*.jpg') ; % GEt all images of the folder
N = length(images) ; % number o fimages
I = imread(images(1).name) ; % crop one to get rect
[x, rect] = imcrop(I) ;
for i = 1:N
I = imread(images(i).name) ; % REad image
I = imcrop(I,rect) ; % crop image
[filepath,name,ext] = fileparts(images(i).name) ;
imwrite(I,strcat(name,'cropped',ext)) ; % Save image
end

8 Comments

Thank you!! It worked perfectly! I just had to change "fileparts(files(i).name)" with "fileparts(images(i).name)" to make it work.
Ohhhh...yes...typo error...
i am not gettde is code right can u help me dir('*.jpg') in place of * what we have to write and when i am run that code i am getting this error Index exceeds matrix dimensions.
Error in facecrop3 (line 3) I = imread(images(1).name) ; % crop one to get rect
Hi there,
Thanks for your answer. I had the same problem and this code also worked perfectly well for me.
If I may ask the experts here, is there any way to replace the original images instead of saving the new images in 'cropped.jpg'?
Thank you
Use tis line at imwrite:
imwrite(I,strcat(name,ext)) ; % Save image
Instead of this:
[filepath,name,ext] = fileparts(images(i).name) ;
imwrite(I,strcat(name,'cropped',ext)) ; % Save image
try this:
fullFileName = fullfile(images(i).folder, images(i).name);
imwrite(I,fullFileName) ; % Save image
Also I'd avoid using i (the imaginary number) as a variable name, and avoid using I because upper case "i" looks too much like 1 (one) and l (lower case L).
Thank you very much dear experts. Your answers really made my day :)
I = imread(images(1).name) ; % crop one to get rect
this line gives error of index matrix dimension exceeds. please suggest some solution.

Sign in to comment.

More Answers (1)

</matlabcentral/answers/uploaded_files/270469/Captureblm.PNG> Hiw can i use this script for detecting crop and saving multiples images

Community Treasure Hunt

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

Start Hunting!