Divide matrix into subgroups where the full matrix is not consistant.

1 view (last 30 days)
Hi,
I am currently working on a CT images of heads and need to divide the full image into 9x9 submatrixes. However the full one cannot be divided into 9x9 with mat2cell as:
""Error using mat2cell
Input arguments, D1 through D2, must sum to each dimension of the input matrix size""
This particular image is 70x52 but these will vary a lot all the time.
In the border there is nothing but zeros and I do not care about them, just the head which is in the middle, which is taking roughly 70% of the image.
As a bonus what I would desire most is how to create optimal subgroups, meaning as few 9x9 as possible but which still cover the entire head.
Thank you very much in advance. If there is anything unclear about the question please let me know and I will formulate it differently.

Answers (1)

Harsh Sanghai
Harsh Sanghai on 23 Mar 2023
Hi,
To divide a matrix into submatrices of equal size, you can use the "reshape" function instead of "mat2cell". "reshape" can only divide a matrix into submatrices of equal size, so you'll need to pad your image with zeros to ensure it can be evenly divided into 9x9 submatrices.
To create optimal subgroups that cover the entire head, you can use a sliding window approach. The idea is to slide a 9x9 window over the head and record the positions where the window covers non-zero pixels. Then, you can group these positions into subgroups that cover the entire head.
Example:
% Load the image
image = imread('head_ct.png');
% Extract the head region
head_region = image(size(image, 1)*0.15:end, :, :);
% Initialize a binary mask that indicates which pixels are non-zero in the head region
mask = head_region > 0;
% Slide a 9x9 window over the head region and record the positions where the window covers non-zero pixels
positions = [];
for i = 1:size(head_region, 1)-8
for j = 1:size(head_region, 2)-8
window = mask(i:i+8, j:j+8);
if sum(window(:)) == 81
positions = [positions; i, j];
end
end
end
% Cluster the positions into subgroups that cover the entire head
[idx, C] = kmeans(positions, ceil(size(positions, 1)/9));
subgroups = cell(1, max(idx));
for i = 1:max(idx)
subgroups{i} = positions(idx == i, :);
end
% Display the subgroups
figure;
imshow(head_region);
hold on;
colors = hsv(max(idx));
for i = 1:max(idx)
scatter(subgroups{i}(:, 2), subgroups{i}(:, 1), 5, colors(i, :), 'filled');
end

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!