4
votes

I'm using python and OpenCV. I have a (rectangle or anything) kernel and trying to perform some morphological transformations. My question is what about image boundaries?

For example, how does openCV decide in kernel's elements outside boundaries for dilation? Does it ignore them or use its neighbor's value?

1
As far as I know, it ignores it, same way as a 2D kernel. Do you have a working code that shows a example ? - Cristiano Araujo
It automatically creates a border. If not specified differently is BORDER_CONSTANT with value depending on the morphological operation. I'll post a complete answer later if nobody does it before. - Miki
@Miki Can you post the complete answer today please? - zinon
@CristianoAraujo It's from the OpenCV tutorial the code. You can find it here http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html?highlight=morphological - zinon
@zinon please let me know if my answer is ok, or if you need additional info. - Miki

1 Answers

3
votes

As reported by OpenCV documentation for morphologyEx:

C++: void morphologyEx(InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )

Python: cv2.morphologyEx(src, op, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]) → dst

You see that the function by default create a border with a constant value. This value depends on the type of morphological operation and is defined by morphologyDefaultBorderValue():

//! returns "magic" border value for erosion and dilation. 
//! It is automatically transformed to Scalar::all(-DBL_MAX) for dilation.
static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); }

which will be then corrected for the actual matrix type. So, for CV_8U matrix the border values are either 0 (for dilate) or 255 (for erosion).

Note that all others morphological operations are different sequences of dilate and erode.

The border length is defined in the FilterEngine that actually performs the morphological operation as:

 int borderLength = std::max(ksize.width - 1, 1);

where ksize is the size of the structuring element.

So, by default OpenCV creates the additional boundaries needed (of the correct borderLength according to the kernel), with a specific value. This value guarantees that the morphological operation is consistent across boundaries.