resize an image by deleting columns
2 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Image Analyst
2016-3-29
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.
更多回答(1 个)
Image Analyst
2016-3-29
编辑:Image Analyst
2016-3-29
That does not do it. The help says for any(): "Determine if any array elements are nonzero" So any(a) will give any columns that have a non-zero in them. Then, if you delete those, all you'll be left with are the columns that are all 100% zero. Perhaps you want this:
a(:, ~any(a))=[]; % Delete any column with 1 or more zeros in it.
or this:
a(:, all(a))=[]; % Delete column if all elements in it are zero.
OK, now, I don't understand what "I want to leave just one zero-value column" means. What if you have 50 rows and 100 columns and columns 1, 4, and 6 have 23 zeros in them, and columns 40, 41, and 45 have 50 zeros (so they are zero in all rows)? Which columns do you want to delete, and where exactly do you want to insert an all-zero column as a separator?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!