function g = bwper48(f,conn)
%BWPER48 Find perimeter pixels in Binary and Gray scale image.
%G = BWPER48(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 as default
%conn parameter controls the connectivity type:
% if conn = 4 , then 4-connectivity is used
%if conn = 8 , then 8-connectivity is used
%if conn = otherwise, error must  display to the user
%Gray scale image must be converted to binary

if ((conn ~= 4) & (conn ~= 8))
    error('enter 4 for 4-connectivity or 8 for 4-connectivity');
end
[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 (conn == 4)
            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
        if (conn == 8)
            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|f(x-1,y-1)==0 ...
            |f(x-1,y+1)==0|f(x+1,y-1)==0|f(x+1,y+1)==0))
            g(x,y)=1;
            else
            g(x,y) =0;
            end
        end
    end
end
%calling the function in matlab mode as the following
%>> f = imread('circbw.tif'); %Binary image
%>> g = bwper48(f,4);
%>> g1 = bwper48(f,8);
%>> imview(g1)
%>> imview(g)
%>> f = imread('pout.tif'); %Gray scale image
%>> g = bwper48(f,4);
%>> g1 = bwper48(f,8);
%>> imview(g1)
%>> imview(g)