File Exchange

image thumbnail

Connect Pixels

version (4.06 KB) by Keith Coffman
Connect pixels into a continuous boundary


Updated 13 May 2016

View Version History

View License

Checks each pixel of a logical array to see if it is connected to other pixels in at least two directions. If it's not, it attempts to draw connections to the nearest unconnected pixel until it is, or until it reaches the maximum layer, rMax.
The region and checking order of nearby pixels are given by the edgeVecs vector (see edgeVecs folder), and r indexes the layers to check.

The goal is to take an outline with holes and breaks and create a continuous boundary which can then be used with e.g. imfill(mask,'holes') to create a contiguous region.

The behavior of the algorithm can be changed by editing the edgeVecs array, which makes it very flexible to specific applications, while still allowing a general user to use a common pattern from the sample folder.

I have optimized it as much as possible and created a mex function which is very fast.

Cite As

Keith Coffman (2021). Connect Pixels (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (8)

Md Shamim Hossain

Thanks for the code

Fahd Qureshi

一平 荣

thx a lot for helping me to solve a big problem!

Oded Scharf

thanks a lot! after the changes that David and Fengyi suggested it worked great!


Thank you very much!

Fengyi Gao

I think I know ,cancel the note between line 9 to 13 ,and set the N =rMax ,also change the line 22 like the David said ,it works well ! thx very much!

Fengyi Gao

thanks for your code ,but I want to ask where is the edgeVecs folder?


Nice code, thank you for your submission.
I found a small bug on the while condition in line 22 in connectDots.m, it should be: while connected < 2 && r <= rMax-1
Otherwise we have an index out of bounds problem for r=rMax

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired by: Bresenham optimized for Matlab

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!