MATLAB Answers

How to crop patches from an image portion determined by a mask?

8 views (last 30 days)
M J
M J on 4 Dec 2020
Edited: M J on 5 Dec 2020
Hi everyone,
I was able to generate multiple patches cropped out of images (and group them in a single folder) using the code below. I would simply like to know whether it is possible to (1) specify a mask ignoring the background of my jpg files (I have already done this before and it works fine) and (2) generate patches cropped only from the portion of interest specified by the mask. Is there a way I can modify my code (below) to do this? I thope this makes sense! :)
Thank you!!
Best,
foldername = 'classTest';
listofimages = dir(fullfile(foldername,'*.jpg'));
for i = 1:length(listofimages)
path = foldername + "/" + listofimages(i).name;
extractedimagesfolder = sprintf('extractedimages_%s', listofimages(i).name(1:end-4));
if ~exist(extractedimagesfolder,'dir')
mkdir(extractedimagesfolder)
end
rgbImage = imread(path);
figure; imshow(rgbImage);
[rows, columns, numColorChannels] = size(rgbImage);
subImageWidth = 500;
overlap=150;
stepSize = subImageWidth-overlap;
count=0;
% extract overlapping patches
for row = 1 : stepSize : rows
row2 = min(row + subImageWidth - 1, rows);
for col = 1 : stepSize : columns
col2 = min(col + subImageWidth - 1, columns);
subImage = rgbImage(row:row2, col:col2, :);
baseFileName = sprintf('%d.jpg', count);
fullFileName = fullfile(extractedimagesfolder, baseFileName);
imwrite(subImage, fullFileName);
count=count+1;
end
end
end
  7 Comments
M J
M J on 5 Dec 2020
  1. Let's say I have an image of a lion in a savanna. My "object" of interest is the lion.
  2. I would like to isolate the object of interest (i.e. the lion - see image below) from the rest of the image and extract overlapping square patches (depicted in red - assume they all have the same dimension) only from the isolated object of interest, and store them in a new folder.
I apologize in advance If that doesn't make sense. In any case, thank you for your time.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!