Creating Patches for all images in a directory
1 次查看(过去 30 天)
显示 更早的评论
I have a program that takes an image and create patches (28*28) from that image and then saves each patches as separate images.
fullFileName='demo.jpg';
rgbImage = imread(fullFileName);
imshow(rgbImage);
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
drawnow;
[rows columns numberOfColorBands] = size(rgbImage)
blockSizeR = 28; % Rows in block.
blockSizeC = 28; % Columns in block.
wholeBlockRows = floor(rows / blockSizeR);
blockVectorR = [blockSizeR * ones(1, wholeBlockRows)];
wholeBlockCols = floor(columns / blockSizeC);
blockVectorC = [blockSizeC * ones(1, wholeBlockCols)];
if numberOfColorBands > 1
ca = mat2cell(rgbImage, blockVectorR, blockVectorC, numberOfColorBands);
else
ca = mat2cell(rgbImage, blockVectorR, blockVectorC);
end
plotIndex = 1;
numPlotsR = size(ca, 1);
numPlotsC = size(ca, 2);
for r = 1 : numPlotsR
for c = 1 : numPlotsC
fprintf('plotindex = %d, c=%d, r=%d\n', plotIndex, c, r);
subplot(numPlotsR, numPlotsC, plotIndex);
rgbBlock = ca{r,c};
newimage=sprintf('demo%03d', plotIndex);
imshow(rgbBlock);
imwrite(rgbBlock, [newimage, '.jpg']);
[rowsB columnsB, numberOfColorBandsB] = size(rgbBlock);
caption = sprintf('Block #%d of %d\n%d rows by %d columns', ...
plotIndex, numPlotsR*numPlotsC, rowsB, columnsB);
title(caption);
drawnow;
plotIndex = plotIndex + 1;
end
end
Now I want this program to take all images from a given directory (say, C:/folder/) and create patches for each of the images. For example- If there are 10 images in the directory,then it will create (10*64=640) patches Please help me out on this.
回答(1 个)
Mahesh Taparia
2019-8-26
Hi,
To read the images from a folder, firstly you need to give the path of that folder, then run a loop to read each image, create a patch of required size and save it. You can use ‘dir’ to list the contents of a folder.
You can follow:
Image_folder=dir('PATH TO FOLDER\*.jpg');
N = length(Image_folder);
for i=1:N
I=strcat('PATH TO FOLDER\',Image_folder(i).name);
rgbImage=imread(I);
%%
%%ADD YOUR CODE FOR PATCH EXTRACTION OF 1 IMAGE
%%
end
5 个评论
Stephen23
2019-8-30
编辑:Stephen23
2019-8-30
@Mahesh Taparia: your code produces quite a few warnings in the MATLAB editor, which should be fixed. See also:
Note that fullfile is preferred over string concatenation.
Guillaume
2019-8-30
In addition, the floor in the block count calculations are pointless. If floor does have to do some rounding because the image size is not a multiple of the block size, then the mat2cell call will fail. Ideally, an assert should be added or the calcuation of the block vectors should be improved to add the leftover pixels.
Also, the if is also pointless. When numberOfColorBands is 1, the two mat2cell calls do exactly the same.
I know both of these were in the original code, but there's no reason not to improve it.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!