How to get find() results as a matrix?
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
dpb
2015-10-30
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 个评论
dpb
2015-11-3
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...
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!