简体   繁体   中英

How to find the first and last non-zero values for column and row in an image?

I'm having trouble, because I have this image, what I want to do is just work with the pixels that aren't black. But I have to find the first and last nonzero values to define the boundaries were I will work, the problem is that I can find the first nonzero values(rowandcolumn), but in the last for the column appears the value 1799,and my image is 499x631x3 uint8 , and it should be 533. What is the problem??

My code below:

%Find where the image begins and starts
[r_min, c_min]=find(movingRegistered(:),1,'first');
[r_max, c_max]=find(movingRegistered(:,:),1,'last');

Image link https://www.dropbox.com/s/6fkwi3xbicwzonz/registered%20image.png?dl=0

To find the row index corresponding to the first nonzero element of each column:

A2 = logical(any(A,3)); %// reduce to 2D array, which equals 0 if all three color
                        %// components are 0, and 1 otherwise
[~, row_first] = max(A2,[],1); %// the second output of `max` gives the row index of
                               %// the first maximum within each column

To find the last :

[~, row_last] = max(flipud(A2),[],1); %// matrix upside down to find last, not first
row_last = size(A,1)-row_last+1; %// correct because matrix was upside down

To find the first and last in linear indexing sense: compute A2 as above and apply your code to that:

[r_min, c_min]=find(A2,1,'first');
[r_max, c_max]=find(A2,1,'last');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM