В основном вам нужно найти связанные компоненты в матрице с помощью функций из панели инструментов обработки изображений (как было указано @ Maurits )
Если у вас все еще есть проблемы, рассмотрите следующий код:
%# matrix
A = [
1 1 0 1 0 0
0 0 0 0 0 1
1 0 1 0 1 1
1 0 0 0 0 0
];
BW = logical(A);
%# find connected components (4-connected neighborhood)
CC = bwconncomp(BW, 4);
%# find blocks with two or more connected 1's
idx = ( cellfun(@numel,CC.PixelIdxList) > 1 );
num = sum(idx);
ответ, как и ожидалось:
>> num
ans =
3
В качестве дополнительного шага мы можем построить матрицы, чтобы помочь визуализировать результат:
%# update connected components to those found only
CC.PixelIdxList = CC.PixelIdxList(idx); %# pixel list
CC.NumObjects = sum(idx); %# number of blocks
%# show matrix with blocks found
RGB = label2rgb(labelmatrix(CC), 'lines', [0 0 0]);
h(1) = subplot(121); imshow(BW)
h(2) = subplot(122); imshow(RGB)
title( sprintf('Number of blocks = %d',CC.NumObjects) )
%# plot grid lines
X = 1:size(A,2); Y = 1:size(A,1);
vx = repmat(X+0.5,[2 1]); vx(end+1,:) = NaN;
vy = repmat([Y(1)-0.5;Y(end)+0.5;NaN],[1 size(vx,2)]);
hy = repmat(Y+0.5,[2 1]); hy(end+1,:) = NaN;
hx = repmat([X(1)-0.5;X(end)+0.5;NaN],[1 size(hy,2)]);
line('XData',[vx(:);hx(:)], 'YData',[vy(:);hy(:)], 'Parent',h(1), ...
'LineWidth',1, 'Color',[0.8 0.8 0.8], 'HandleVisibility','off')
line('XData',[vx(:);hx(:)], 'YData',[vy(:);hy(:)], 'Parent',h(2), ...
'LineWidth',1, 'Color',[0.8 0.8 0.8], 'HandleVisibility','off')