MATLAB: Resize an image by deleting columns

horizontal compressionImage Processing Toolboxresize an image by deleting columns

How are you everyone!
Today I have a binary image and I want to resize it by deleting columns which have zero values, for this purpose I can use this command
a(:,any(a))=[];
the problem with this command is that I want to leave just one zero-value column to keep regions separated. Could you help me to solve this problem
Thank you!

Best Answer

This will do it:
% Create sample image data
m = 255*[0 1 0 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0;
0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 0;
0 1 1 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0]
% Find all zero columns
totallyBlankColumns = ~any(m, 1)
measurements = regionprops(logical(totallyBlankColumns), 'PixelIdxList');
% Make an array to keep track of which columns we will want to remove.
columnsToDelete = false(1, length(totallyBlankColumns));
% For each region, if it's more than 3 columns, keep track
% of which columns to delete (the second and subsequent columns in that run).
for region = 1 : length(measurements)
% Get indexes of this run of zeros.
theseIndexes = measurements(region).PixelIdxList
% If there are more than 1 of them, delete the second onwards in this run.
if length(theseIndexes) >= 2
columnsToDelete(theseIndexes(2:end)) = true;
end
end
% Get a new m by removing those columns
mCompressed = m(:, ~columnsToDelete)
Shows in command window:
m =
0 255 0 255 0 0 0 0 255 255 0 0 0 255 255 0 0 0
0 255 255 255 0 0 0 0 255 255 0 0 0 255 0 0 0 0
0 255 255 255 0 0 0 0 255 255 0 0 0 255 255 0 0 0
totallyBlankColumns =
1 0 0 0 1 1 1 1 0 0 1 1 1 0 0 1 1 1
theseIndexes =
1
theseIndexes =
5
6
7
8
theseIndexes =
11
12
13
theseIndexes =
16
17
18
mCompressed =
0 255 0 255 0 255 255 0 255 255 0
0 255 255 255 0 255 255 0 255 0 0
0 255 255 255 0 255 255 0 255 255 0
And you can see the array is compressed horizontally so that there is only a single column of zeros separating the columns that have something in them. If it works, please accept the answer.