Logical Indexing and Masking

  • Logical indexing is a way to address specific elements in a matrix. Because images are just matrices, we can also use logical indexing to address, change, and “photoshop” particular pixels in an image.

  • true(1) false (0)

  • This technique allows for efficient manipulation of image data, enabling operations such as filtering, masking, and selective color adjustments.

  • < less than

  • <= less than or equal to

  • > greater than

  • >= greater than or equal to

  • == equal to

  • ~= not equal to

  • & combine more than one relational operator


Let’s explore logical indexing with a simple example.

We want to explore where A>15

Create matrix A:

» A = [ 11 12 13 ; 14 15 16; 17 18 19]

A =

11 12 13

14 15 16

17 18 19

Create matrix B:

» B = A>15

B =

0 0 0

0 0 1

1 1 1

What is B?

  • B is a logical array. We will define this as a “mask” going forward

  • B has a value of 1 in the corresponding position of A where the elements satisfy the c condition B>15. If the condition is not met, B has a value of 0.

  • NOTE: The mask is the same size as the original matrix


How can we use our mask to operate on A?

Evaluate A at the mask:

» values = A(mask)

values =

17

18

16

19

(returns the values where A is true)

What if we want the inverse of the mask?

» values2 = A(~mask)

values2=

11

12

13

14

15

(returns the values where A is false. We are asking for “not the mask.”


We can apply matrix indexing to change the values of elements in our matrix

Change the value 12 in A to 100:

A(1,2) = 100

A =

11 100 13

14 15 16

17 18 19

How can we apply our mask to change values in our matrix?

A(mask) = 50

A =

11 12 13

14 15 50

50 50 50


What if we want to use our mask to sub all the positions in our mask with values from another matrix?

C =

5 5 5

5 5 5

5 5 5

A(mask) = C(mask)

A =

11 12 13

14 15 5

5 5 5

NOTE: MATLAB operated on our original matrix A and we have no way to get it back! In practice, it is better to first make a new matrix on which you will operate, THEN apply the mask. Otherwise, you lose your unaltered data or picture!!

step 1: AA = A

step 2: AA(mask) = C(mask)


How does this apply to our images?

  • We can use relational operators to select the pixels in our images that we could like to manipulate. This will be our mask.

  • Then we can apply our mask to the original image where we would like to change the pixels, i.e the examples from the previous slides on a much larger scale!

A(mask) = C(mask)

A=

11 12 13

14 15 5

5 5 5