Asked by rio
on 20 Jun 2013

i have been working for my thesis about image segmentation. i have this matrix

a =

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0

and then i want to find the first x,y with binary 1 using for sintax this is the one i use but its not working

---------------------------------------------

function [x1,y1,x2,y2,x3,y3,x4,y4]=gedge(x)

[m,n]=size(x);

% upper edge xy

for i=1:m for j=1:n if(x(i,j)==1) x1=i; y1=j; break end end end

% left edge xy

for j=1:n for i=1:m if(x(i,j)==1) x2=i; y2=j; break end end end

% bottom edge xy

for i=m:-1:1 for j=n:-1:1 if(x(i,j)==1) x3=i; y3=j; break end end end

% right edge xy

for j=n:-1:1 for i=m:-1:1 if(x(i,j)==1) x4=i; y4=j; break end end end

%for the cropping

y=x(x1:x4,y2:y3);

-----------------------------------------------------------------

so i want to erase the 0 binary for my image segmentation. it will be this matrix:

a =

0 1 1 1 0 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0

please help recorrect my sintax code. Thanks

*No products are associated with this question.*

Answer by Elliot Olsen
on 20 Jun 2013

Accepted answer

Hi,

Here is my implementation. Let me know if there is something you do not understand.

[r,c] = size(a);

% Starts at bottom row and removes rows that have nothing in them. for i = fliplr(1:r) if sum(a(i,:)) == 0 a(i,:) = []; else break; end end

% Starts from right-most column and removes columns with nothing in them. for i = fliplr(1:c) if sum(a(:,i)) == 0 a(:,i) = []; else break; end end

% Starts at top row, counts number of empty rows until it gets to a % non-empty row. These cannot be removed immediately or it will screw up % the for-loop. top_count = 0; for i = 1:r if sum(a(i,:)) == 0 top_count = top_count + 1; else break; end end

% Starts at left-most column, counts number of empty columns until it gets % to a non-empty column. These cannot be removed immediately or it will % screw up the for-loop. left_count = 0; for i = 1:c if sum(a(:,i)) == 0 left_count = left_count + 1; else break; end end

% Now left-most empty columns and top empty rows can be safely removed. if top_count > 0 a(1:top_count,:) = []; end if left_count > 0 a(:,1:left_count) = []; end

Answer by Jonathan Sullivan
on 20 Jun 2013

Edited by Jonathan Sullivan
on 20 Jun 2013

It's really simple if you use the functions **find** and **any**. See below:

ind1 = find(any(x == 1,2),1); ind2 = find(any(x == 1,2),1,'last'); ind3 = find(any(x == 1,1),1); ind4 = find(any(x == 1,1),1,'last');

y = x(ind1:ind2,ind3:ind4);

Answer by Andrei Bobrov
on 20 Jun 2013

out = a(any(a,2),any(a));

Opportunities for recent engineering grads.

## 0 Comments