0

I retrieved all non-white pixel from an image :

[ii, jj] = find(BlackOnWhite < 255)

Then I tried to index those pixel coordinates to a matrix :

image(ii, jj) = 0

But zeros do not appear in the expected places. How can I put zeros only in the places specified by pairs from ii and jj (i.e. [ii(1), jj(1)], [ii(2), jj(2)] etc.)?

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
Rom
  • 225
  • 2
  • 11
  • 1
    But I don't have the expected result. Which are the expected results? – Ander Biguri Oct 10 '18 at 12:49
  • 1
    Possible duplicate of [Matlab: assign to matrix with column\row index pairs](https://stackoverflow.com/questions/7119581/matlab-assign-to-matrix-with-column-row-index-pairs) – Cris Luengo Oct 10 '18 at 13:01

2 Answers2

6

A simple way to do that is to use linear indexing. This means using a single index that traverses all entries in the matrix (down, then across). In your case:

  • Use find with one ouput. This gives the linear indices of the desired pixels.
  • Use that to index into the matrix.

So:

ind = find(BlackOnWhite < 255);
image(ind) = 0;

You can even remove find and use logical indexing. This means that the result of the logical comparison is directly used as an index:

ind = BlackOnWhite < 255;
image(ind) = 0;

The problem with the code shown in your question is that ii and jj are being used as "subscript indices". This selects all pairs formed by any value from ii and any value from jj, which is not what you want.

If you have subscripts ii and jj like in your question and you need to only select corresponding values from each subscript (instead of all pairs), you can use sub2ind to convert to a linear index:

[ii, jj] = find(BlackOnWhite < 255);
image(sub2ind(size(image), ii, jj)) = 0;
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
3

It doesn't work because MATLAB treats the subscripts as a grid, which means roughly "set all intersection of any of ii and any of jj to zero" and not "set the locations specified by these separate pairs of coordinates to zero".

In some cases (but not this one) you might need to convert a set of subscripts to indices, in which case I suggest familiarizing yourself with sub2ind.

As mentioned in the other answer(s), the best thing to do in your case is simply:

image(BlackOnWhite < 255) = 0;
Dev-iL
  • 23,742
  • 7
  • 57
  • 99