How to get find() results as a matrix?
11 views (last 30 days)
Show older comments
Hi,
I have a binary image that was obtained from a color image (both were attached here). The background of the segmented image is black and the main object is white. I'm trying to use that binary image to get only the main object of the color image by using find() function.
I was able to do it using the following code:
I = imread(<binaryImage>);
I2 = imread(<color image>);
IMNONZERO = find(I); % this code returns only indexes of non-zero values
I3 = I2(IMNONZERO); % this gets all indexes of IMNONZERO in the I2 color image
imshow(I3);
This is my question: I saw that find() returns linear indexes. Also, I tried [row, col] = find(I) and it brings me the indexes of non-zero values as 2 separated arrays (one for row and another for column). However, I would like to know if it's possible to obtain those indexes as a regular matrix.
Is it possible?
Thank you in advance,
Queila
0 Comments
Accepted Answer
dpb
on 30 Oct 2015
Yes, if you wrap the find call inside ind2sub--
ijNONZERO = ind2sub(find(I),size(I));
But, you really don't need them for any purpose shown above.
Also, you can do w/o find entirely --
I3=I2(I~=0); % get all locations not zero in I from I2
However, I'm guessing this isn't going to work as you're hoping unless the image I has very special properties such that it returns another square/rectangular array. I'd guess imshow isn't happy with it has you're still going to get a vector of returned values, NOT a rectangular grid.
That's not doable by such logic and it's not a syntax issue it's a fundamental property of the characteristic of the image--there's no guarantee at all it will return such a set that can be arranged to be a valid image array.
2 Comments
dpb
on 3 Nov 2015
How do you get three ones/row from the original if you "want to remove all zeros"? That would leave a 3x2 array, not 3x3.
If it's regular as above, then
A=reshape(A(A~=0),size(A,1),[]);
does what I think you're asking.
If the area is not regular such that there are zeros scattered within the area that is otherwise nonzero, then you'll have to do something like --
>> A=[A(:,1:3) A]; A(2,4)=5 % another dummy array...
A =
0 1 1 0 1 1 0
0 2 2 5 2 2 0
0 3 3 0 3 3 0
>> A(:,all(A==0))=[] % remove all columns fully zero remaining rectangular
A =
1 1 0 1 1
2 2 5 2 2
3 3 0 3 3
>>
If there are also rows; then use the second optional DIM option with all for them...
A(all(A==0,2),:)=[] % remove all rows fully zero
You might, depending on the need, want to check that there isn't a row/column in the middle rather than just edges first, that I don't know about whether would be a need or not...
More Answers (1)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!