# Grayscale morphology

Hello I've been trying to understand the grayscale dilation operation using the following example, but my results are different.

$I = \begin{pmatrix} \bf{5} & 2 & 4 \\ 1 & -3 & 1 \end{pmatrix}$

is the image to be dilated, and the structuring element is

$S = \begin{pmatrix} 0 & x & \bf{0} \\ 0 & 2 & -1 \end{pmatrix}$

I have marked the origin in the structuring element and the image (the bold $\bf5$ in the top left of $I$ and the bold $\bf0$ in the top right of $S$), and $x$ means that the pixel is not part of the structuring element. The correct answer is supposed to be

$\begin{pmatrix} 5 & 2 & 5 & 2 & 4 \\ 5 & 7 & 4 & 6 & 3 \\ 1 & 3 & 1 & 3 & 0 \end{pmatrix}$

but my result is

$\begin{pmatrix} 4 & 7 & 5 & 6 & 4 \\ 5 & 3 & 5 & 3 & 4 \\ 1 & -3 & 1 & -3 & 1 \end{pmatrix}$

What I did was, put the center of the s.e. in each pixel, for each pixel in the neighborhood sum pixel to pixel their values and take the max of the neighborhood as the new value.

For example, when the s.e. is in pixel $I(0,1)$ then

$$\max( I(0,0)+SE(0,-1), I(0,1)+SE(0,0), I(1,0)+SE(1,-1), I(1,1)+SE(1,0) ) =\\ \max(5+x=x, 2, 3, -4)$$

1. Can someone explain to me what is the correct way of doing this?
2. In the dilation do we need to flip the structuring element? What about erosion?

According to this paper, the grayscale dilation of image $I$ by a non-flat structuring element $S$ is defined as follows:

$[I ⊕ S](x,y) = \displaystyle\max_{(s,t)∈S}\{I(x-s,y-t)+S(s,t)\}$

Since the origin of the structuring element is in the top right corner, we have that $s∈[0,1]$ and $t∈[-2,0]$ excluding the point $(s,t)=(0,-1)$. So using your example of element $I(0,1)$ we have the following:

$[I ⊕ S](0,1)=\max\{I(0,3)+S(0,-2),\ I(-1,3)+S(1,-2),\ I(-1,2)+S(1,-1),\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ I(0,1)+S(0,0),\ I(-1,1)+S(1,0)\}$

$=\max\{0+0,0+0,0+2,2+0,0+(-1)\}=\max\{0,0,2,2,-1\}=2$

Which is the correct value for element $(0,1)$ in the dilated matrix. You can then simply apply the formula to the other $(x,y)$ value pairs of interest to obtain the final result.

The definition of erosion (and the other morphological operations) can also be found in that paper and applied in the same manner.