Read, Crop and then Save multiple images - from multiple folders

Hi there, I have working code for reading, cropping and saving an image and now I hope to tackle cropping multiple images in a folder.
I used answers posted on this forum for the same purpose, yet sadly I did not have any luck in getting it working.
The working code I have for reading, cropping and saving just one image is as follows:
imshow('1-01-H PS.jpg');%load image
img = imread('1-01-H PS.jpg');
a = img(250:1565,1480:2370);
a = img(250:1565,1480:2370,:);
imshow(a)
imwrite(a,'Cropped 1-01-H PS.jpg');
imshow('Cropped 1-01-H PS.jpg');
I essentially want to loop this through each folder. Each folder contains 10-40 images, all to be cropped to the same dimensions above.
The advice I saw on this forum was as followed:
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
fullFileName = fullfile(images(i).folder, images(i).name);
imwrite(I,fullFileName) ; % Save image
end
Unfortunately I could not get the two to marry together. I am using 2019a release. Any advice/suggestions would be much appreciated!

Respuestas (1)

Ameer Hamza
Ameer Hamza el 20 de Abr. de 2020
Editada: Ameer Hamza el 21 de Abr. de 2020
Unfortunately, you are overwriting the original files with the cropped images. I hope that you have backed-up all the images. Try this. I have changed the imwrite line.
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
fullFileName = fullfile(images(i).folder, ['cropped' images(i).name]);
imwrite(I,fullFileName); % Save image
end
To loop through multiple directories:
If your folder structure is like this
filder1:
image1
image2
..
imageN
folder2:
image1
image2
..
imageN
..
..
folderN:
image1
image2
..
imageN
then you can change the first line of the code to
images = dir('*/*.jpg');
and if there are several levels of subfolders and you are at the top-level, then you can get the name of all the files in the current directory and subdirectory with
images = dir('**/*.jpg');
Apply the second options with care. It will recursively search the directories for jpg files.

9 comentarios

Hi Ameer, thank you very much for your fast response.
Thank you for pointing out that I was overwriting the original files, thankfully I always have a backup because I know what I'm like…
I have tried the code you kindly suggested. Unfortunately I am still getting errors:
Error using fopen
Unable to find file. Ensure file exists and path is valid.
Error in imwrite (line 517)
fid = fopen(filename, 'a');
Error in TESTCropAllImagesInAFolder (line 9)
imwrite(I,['Cropped ' fullFileName]); % Save image
I believe my files and path is correct, would you kindly advise what I am missing/doing incorrectly?
I made a mistake in my code. Please try the updated code.
Yes, but she has multiple folders, so you need to show her how to use ** in dir(), or how to use imageDatastore() to recursively go into each folder and process the files.
Thanks for pointing out, I missed the part about multiple folders.
You forgot to construct the full input filename in case the image is not in the current folder. Fixed code is below:
clc; % Clear the command window.
fprintf('Beginning to run %s.m.\n', mfilename);
% Get a list of all images.
folder = pwd; % wherever... can call uigetdir() if you want.
filePattern = fullfile(folder, '**/*.jpg');
images = dir(filePattern); % Get all images of the folder
if isempty(images)
errorMessage = sprintf('No images found in %s', folder);
uiwait(errordlg(errorMessage));
return;
end
numberOfImages = length(images) ; % number of images
thisFileName = fullfile(images(1).folder, images(1).name);
thisImage = imread(thisFileName) ; % crop one to get rect
imshow(thisImage);
axis('on', 'image');
caption = sprintf('Please click and drag out a cropping rectangle. Double click inside to accept it');
title(caption, 'FontSize', 15);
uiwait(helpdlg(caption));
[x, rect] = imcrop(thisImage);
for k = 1:numberOfImages
thisFileName = fullfile(images(k).folder, images(k).name);
fprintf('Cropping image %d of %d : %s\n', k, numberOfImages, thisFileName);
thisImage = imread(thisFileName) ; % Read image
subplot(1, 2, 1);
imshow(thisImage);
axis('on', 'image');
caption = sprintf('%s, image %d of %d', images(k).name, k, numberOfImages);
title(caption, 'FontSize', 15, 'Interpreter', 'none');
croppedImage = imcrop(thisImage, rect) ; % Crop image
subplot(1, 2, 2);
imshow(croppedImage);
axis('on', 'image');
drawnow;
fullOutputFileName = fullfile(images(k).folder, ['cropped' images(k).name]);
% Save cropped image into source image's folder.
imwrite(croppedImage, fullOutputFileName);
pause(0.5); % Delay long enough to see the cropping.
end
Ah! I missed that too ?‍♂️. I think you should add this comment as an answer to this question. It is much more detailed than my answer and addresses other issues too.
Wow, truly incredible! The code has worked brilliantly.
Thank you both for your time and efforts in assisting me with this issue. It has saved me a great deal of time and it is great to see the code so I can keep learning - I certainly wouldn't have been able to write all of that!
Thank you very much for your inputs :)
Read, imwrite multiple LBP images - from multiple folders....
please "Image Analyst" i need your help am stuck, i want to read and inwrite the LBP multiple image from multiple folder in a folder but am having errors..
below is my code..
function [lbparray] = LBPfun(dir, path)
filesInfor1 = {dir.name};
image_array = [];
var_matrix = [];
dim = 0;
im = {};
TrainingData = {};
outputFolder = fullfile('C:\Users\uba.janefrances\Desktop\Thesis\All_Faces\LBP_images\LBP Output Images');
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
for k=1:numel(filesInfor1)
% %read image one after the other
img = imread(strcat(path,'\',filesInfor1{k}))
img=imresize(img, [64 64]);
img = rgb2gray(img);
% figure();
% imshow(img);
imgg=LBP2(img);
lbpImage = (imcomplement(uint8(imgg)));
imshow( lbpImage);
cd('C:\Users\uba.janefrances\Desktop\Thesis\All_Faces\LBP_images\LBP Output Images\');
% Now do the writing
imwrite(uint8( lbpImage), 'lbpoutputimage.bmp','bmp');
end
AM WORKING ON SIX CLASSES OF IMAGE DATASET ANGER, DISGUST, FEAR,HAPPY,SAD AND SUPRISE AND i want to read and inwrite the LBP multiple image from multiple folder (6) in a folder (6) but am having errors..
below is my code..
function [lbparray] = LBPfun(dir, path)
filesInfor1 = {dir.name};
image_array = [];
var_matrix = [];
dim = 0;
im = {};
TrainingData = {};
outputFolder = fullfile('C:\Users\uba.janefrances\Desktop\Thesis\All_Faces\LBP_images\LBP Output Images');
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end
for k=1:numel(filesInfor1)
% %read image one after the other
img = imread(strcat(path,'\',filesInfor1{k}))
img=imresize(img, [64 64]);
img = rgb2gray(img);
% figure();
% imshow(img);
imgg=LBP2(img);
lbpImage = (imcomplement(uint8(imgg)));
imshow( lbpImage);
cd('C:\Users\uba.janefrances\Desktop\Thesis\All_Faces\LBP_images\LBP Output Images\');
% Now do the writing
imwrite(uint8( lbpImage), 'lbpoutputimage.bmp','bmp');
end

Iniciar sesión para comentar.

Categorías

Más información sobre Convert Image Type en Centro de ayuda y File Exchange.

Preguntada:

el 20 de Abr. de 2020

Comentada:

el 23 de Nov. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by