So I started digging into Matlab's imfill
code, but quickly found that the code it provides is just a wrapper for some compiled c or c++ code. For now I'll try to outline an algorithm that should get you what you want. The following algorithm assumes that the regions to be filled contain zero values in the original image.
- Identify contiguous regions of zeros, for instance by:
- creating a new (zero) mask image
- looping over the mask image, and when a position is found that is zero both in the original image and in the mask image, recursively assigning a value to this location in the mask, and to all neighbors who are zero in both the mask and the original. This results in a mask where each contiguous region of zeros in the original image has a unique ID.
- For each contiguous region of zeros, identify all other values that border this region in the original image, taking care to record when a region of zeros borders the edge of the image.
- For each contiguous region of zeros that borders only one value in the original image, and does not border the edge of the image, replace all of those zeros in the original image with the value that they border.
This algorithm is not necessarily efficient. In particular step 1 could probably see some speedup with intelligent use of queues to keep you from looking at the same position multiple times in the recursive calls.