Find perimeter of objects in binary image


  • BW2 = bwperim(BW)
  • BW2 = bwperim(BW,conn)



BW2 = bwperim(BW) returns a binary image that contains only the perimeter pixels of objects in the input image BW. A pixel is part of the perimeter if it is nonzero and it is connected to at least one zero-valued pixel. The default connectivity is 4 for two dimensions, 6 for three dimensions, and conndef(ndims(BW), 'minimal') for higher dimensions. If you do not specify a return value, bwperim displays the result in a figure window.

BW2 = bwperim(BW,conn) where conn specifies the desired connectivity.

Code Generation support: Yes.

MATLAB Function Block support: Yes.


collapse all

Find Perimeter of Objects in Binary Image

Read binary image into workspace.

BW = imread('circles.png');

Calculate the perimeters of objects in the image.

BW2 = bwperim(BW,8);

Display the original image and the perimeters side-by-side.


Input Arguments

collapse all

BW — Input binary imagelogical or numeric matrix that must be 2-D, real, and nonsparse

Input binary image, specified as a logical or numeric matrix that must be 2-D, real, and nonsparse.

Example: BW = imread('circles.png'); BW2 = bwperim(BW);

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical

conn — Connectivity4 for 2-D (default) | 6 | 8 | 18 | 26 | 3-by-3-by-...-by-3 array of zeroes and ones

Connectivity, specified as one of the values in this table or a 3-by-3-by-...-by-3 array of 0s and 1s. The 1-valued elements define neighborhood locations relative to the center element of conn. Note that conn must be symmetric around its center element.



Two-dimensional connectivities


4-connected neighborhood


8-connected neighborhood

Three-dimensional connectivities


6-connected neighborhood


18-connected neighborhood


26-connected neighborhood

Example: BW2 = bwperim(BW,8);

Data Types: double | logical

Output Arguments

collapse all

BW2 — Output binary image containing only perimeter pixels of objectslogical array

Output image containing only perimeter pixels of objects, returned as a logical array.

More About

expand all

Code Generation

This function supports the generation of C code using MATLAB® Coder™. Note that if you choose the generic MATLAB Host Computer target platform, the function generates code that uses a precompiled, platform-specific shared library. Use of a shared library preserves performance optimizations but limits the target platforms for which code can be generated. For more information, see Understanding Code Generation with Image Processing Toolbox.

When generating code, note the following:

  • bwperim supports only 2-D images.

  • bwperim does not support a no-output-argument syntax.

  • The connectivity matrix input argument, conn, must be a constant

MATLAB Function Block

You can use this function in the MATLAB Function Block in Simulink.

Introduced before R2006a

Was this topic helpful?