0

How can I count the number of values that are contiguous in an matrix? For example, if

A= [ 1 0 1 0 0 0 0 \ 1 1 1 0 0 0 1\ 1 1 0 1 1 1 1]

is a 7 by 3 matrix then the result should indicate that there are 12 contiguous values that are "1" (highlighted in bold), that there are 8 contiguous 0 values (highlighted in italics) and one lone 0 value. Code in IDL is preferred but MATLAB would also be helpful.

cmicro
  • 3
  • 2
  • I updated the tag. Thanks! – cmicro May 18 '18 at 21:52
  • You are looking for [Connected Component Analysis](https://en.wikipedia.org/wiki/Connected-component_labeling). In MATLAB that is [`bwlabel`](https://www.mathworks.com/help/images/ref/bwlabel.html) or [`bwconncomp`](https://www.mathworks.com/help/images/ref/bwconncomp.html). – Cris Luengo May 18 '18 at 21:53
  • Thanks for the reply! Could either of these functions help me count the number of contiguous or "touching" numbers? Code examples would be appreciated. – cmicro May 18 '18 at 21:58
  • Now, is there a way to count the maximum number of columns and maximum number of rows that the island/blob expands? I saw that there's a function called "regionprops3" but I'm not sure if there's a simple way of counting the number of rows or columns the blob expands. Thanks! – cmicro Jun 20 '18 at 19:57
  • `regionprops3` is for 3D matrices, for 2D matrices use [`regioprops`](https://www.mathworks.com/help/images/ref/regionprops.html). The `'BoundingBox'` property returns a 4-element vector: `[left, top, width, height]`. `width` would be the number of columns, and `height` the number of rows occupied by the contiguous group. – Cris Luengo Jun 20 '18 at 20:48

1 Answers1

0

This is what you can do in MATLAB using the bwconncomp function. This is a function in the Image Processing Toolbox. I don't know a whole lot about IDL, it might have a similar function.

bwconncomp returns a struct with some information, one of the fields is PixelIdxList, which is a cell array with one element per connected component. Each of these elements is a vector with the indices to one of the array elements in the connected component. For the case of the 1 elements in your example, this cell array will have one vector with 12 values. For the case of the 0 elements, it will have two vectors, one with 1 value and one with 8:

>> A = [ 1 0 1 0 0 0 0 ; 1 1 1 0 0 0 1 ; 1 1 0 1 1 1 1 ];
>> CC = bwconncomp(A==1, 8);
>> cellfun(@numel, CC.PixelIdxList)
ans = 
    12

>> CC = bwconncomp(A==0, 8);
>> cellfun(@numel, CC.PixelIdxList)
ans =
     1     8

The bwconncomp takes 4 or 8 as the second argument. This specifies what are considered connected elements (contiguous values, neighbors). 4 means only the 4 elements N,S,E,W are connected; 8 means also diagonal connections exist (8 neighbors).

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120