MATLAB: What does this code do

detectionimage processing

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,:);

Best 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);