function g = bwper4(f)
%BWPER Find perimeter pixels in Binary and Gray scale image.
%G = BWPERIM(F) returns a binary image containing only the perimeter
%pixels of objects in the input image F
%A pixel is part of the perimeter if 
%it nonzero and it is connected to at least one zero-valued pixel.
%4-connectivity is used in this function
[M N]=size(f);
if(islogical(f)== false)
f = im2bw(f,0.5);
end
g = logical(zeros(M,N));
for x=2:M-1
    for y=2:N-1
        if((f(x,y)==1)&(f(x-1,y)==0|f(x,y-1)==0|...
                f(x,y+1)==0|f(x+1,y)==0))
            g(x,y)=1;
        else
            g(x,y) =0;
        end
    end
end