Store cropped images in for loop

7 views (last 30 days)
I am cropping an image into 16 subsections (4 rows and 4 columns of cropped images). My code runs, but when my cropped images are plotted they are blank. If I manually crop the images, i.e. give each one a unique name and use imcrop and manually set the "rect" portion of imcrop, it works just fine. Could anyone please help on why this is happening/how to fix it?
% Clear variables, close windos, and clear command window
clear all
close all
clc
% Read in image
rgbImage = imread('Image.tif');
% Determine # rows/columns/ColorBands
[rows, columns, ColorBands] = size(rgbImage);
% Enlarge figure to full screen
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Determine locations where image is split
% Current image is split into N subimages
% Number of subimages and spacing between subimages (N should be perfect
% square)
N = 16;
blocks = sqrt(N); % Number of rows/columns
col_spacing = columns/blocks; % Inclusive size of spacing between columns
col_size = col_spacing - 1; % Exclusive size of spacing between columns
row_spacing = rows/blocks; % Inclusive size of spacing between rows
row_size = row_spacing - 1; % Exclusive size of spacing between rows
% Zero out inital arrays
column_breaks = zeros(blocks,1);
row_breaks = zeros(blocks,1);
% Set first value to 1
column_breaks(1) = 1;
row_breaks(1) = 1;
% Set last value to columns/rows
column_breaks(blocks) = columns;
row_breaks(blocks) = rows;
% For loop to determine other positions
for i = 2:blocks
column_breaks(i) = col_spacing*(i-1) + 1;
row_breaks(i) = row_spacing*(i-1) + 1;
end
% Crop Images, crop = cropped subimage matrix
crop = zeros(row_spacing,col_spacing,3,blocks,blocks);
for i = 1:blocks
for j = 1:blocks
crop(:,:,:,i,j) = imcrop(rgbImage, [column_breaks(j) row_breaks(i) col_size row_size]);
end
end
% Display cropped images in subplot
for i = 1:blocks
for j = 1:blocks
subplot(4,4,(i-1)*4+j)
imshow(crop(:,:,:,i,j))
end
end

Accepted Answer

DGM
DGM on 30 Dec 2022
Edited: DGM on 30 Dec 2022
Keep track of array class and data scale when working with images. You likely have integer-class data, but you're storing it in an output array that was implicitly preallocated as 'double'. As a consequence, the data is handled by imshow() and imwrite() as if it's a unit-scale (i.e. [0 1]) float image, when in reality, the data is scaled to the original integer class (e.g. [0 255]).
The easy thing to do is just specify the appropriate class when allocating the output array.
crop = zeros(row_spacing,col_spacing,3,blocks,blocks,class(rgbImage));

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!