Hi Just wondering what this bit of code does in a general sense, so far, i've found that it checks for values in image i1 that arent 255 and lists them in a column matrix. however i dont know what the next bit does or even if im correct.
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);

4 Comments

KSSV
KSSV on 30 Apr 2019
Edited: KSSV on 30 Apr 2019
Simple it extracts a chunk of matrix from a matrix.
Thank you,
In theory how does it do it? im trying to convert it to python however i dont know exactly what its doing
KSSV
KSSV on 30 Apr 2019
It does by the indices.....this option python also has.
Thank you,
Do you know the functions i would use in python for this?

Sign in to comment.

 Accepted Answer

find with one output argument return a vector of linear index. If you give it two output arguments, it returns a row and column vector of the same locations. Unfortunately, it doesn't extend to 3D, you don't get row/column/pages if you ask for three outputs.
If the image matrix had been 2D (greyscale image), the author could have simply used:
[row, column] = find(i1 ~= 255);
However since the image matrix is 3D (colour image) and the author wanted to know in which colour plane the values were found, he asked instead for linear indices and used ind2sub to convert these linear indices into 3D matrix coordinates (row, column, pages)
linearindices = find(i1 ~= 255);
[row, column, page] = ind2sub(size(i1), linearindices);
Note that as I've shown there's no point in building [size(i1,1) size(i1,2) size(i1,3)], it's simply size(i1).
Also the author made a mistake or used very misleading names for his variables. Typically, x is the horizontal coordinates, which is the second output of find and ind2sub, not the first. So using, his variable names:
[y, x, rgb] = ind2sub(size(i1), find(i1 ~= 255));
And since he doesn't care about the 3rd output, he could have used:
[y, x, ~] = ind2sub(size(i1), find(i1 ~= 255));
He then takes the min and max of the rows and columns and crop the image to these.
Note that another way to obtain the same, which is probably more intuitive is with:
[row, col] = find(any(i1 ~= 255, 3)); %find pixels ~= 255 in any colour plane
A = i1(min(row):max(row)-1, min(col):max(col)-1);

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!