Finding specific elements in a Julia array

There are times when it is necessary to extract particular elements from a 2D array. This is especially relevant in image processing using filters which are not square or rectangular in shape. For instance consider the following circular filter with a diameter of 11.

 0 0 0 1 1 1 1 1 0 0 0
 0 0 1 1 1 1 1 1 1 0 0
 0 1 1 1 1 1 1 1 1 1 0
 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1
 0 1 1 1 1 1 1 1 1 1 0
 0 1 1 1 1 1 1 1 1 0 0
 0 0 0 1 1 1 1 1 0 0 0

The task here is to use this filter to extract only the appropriate elements from an associated 11×11 region inside an image. How to do that? Let’s say the variable circFlt holds this filter. The first task is to reshape the filter into a vector – this makes it easier to extract elements. This is achieved using the function reshape() which creates a vector of length 121 elements (line 1). Then a  function is created to represent the elements to be extracted – 1 in this case (line 2). Finally the find() function is used to extract the indices of elements in circFltV that match the function (line 3) – stored in the vector circFltE.

 1   circFltV = vec(reshape(circFlt,1,121))
 2   f(x) = x == 1
 3   circFltE = find(f,circFltV)

Now, let’s say that block holds the 11×11 image region to be processed. The first step is translating this into a vector (blockV) to match circFltV (line 4). Then Julia has a cool function called getindex() which will return the elements of blockV which are associated with the indices in circFltE.

 4   blockV = vec(reshape(block,1,imgSz))
 5   blockC = getindex(blockV,circFltE)

Basically in the 11×11 region in the image, only elements which have an associated 1 in the circular filter are extracted.

NOTE: find can also be used directly on a 2D array, just remember that the vector returned will represent the 2D array in column-major format. Below is a sample piece of code.

juliafind

The second command creates a function to find all values in the array greater than 4. When this is applied to the array a using find(), four indices are retrieved: 5, 7, 9, 10 referring to the values 5 (index 5), 8 (index 7), 9 and 33 (indices 9 and 10 respectively). These can be used to modify only those values in the array.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s