0

I am trying to understand how to control the kernel anchor in dilation's OpenCV. Here is my example code to explain my idea:

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = np.zeros((7, 7))
img[3, 3] = 255
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 2), anchor=(0, 0))
print(kernel)
img = cv2.dilate(img, kernel)
plt.imshow(img, cmap='gray')
plt.show()

and here is the corresponding output:

enter image description here

When I change the kernel anchor as to (0, 1),

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 2), anchor=(0, 1))

I expect that the dilation would be upwards, but I am getting the exact same result. Does anyone have an explanation for this?

Thanks in advance!

Community
  • 1
  • 1
Kasparov92
  • 1,365
  • 4
  • 14
  • 39

1 Answers1

1

You need to set the anchor not in the function cv2.getStructuringElement, but in the function cv2.dilate.

img = cv2.dilate(img, kernel, anchor=(0, 1))

or

img = cv2.dilate(img, kernel, anchor=(0, 0))
Alex Alex
  • 1,893
  • 1
  • 6
  • 12
  • It works, thanks! One more question, why does it feel that anchor (0, 0) and anchor (0, 1) generate reversed output, I mean I expect that anchor (0, 0) dilates downwards and anchor (0, 1) dilates upwards, however, anchor (0, 0) dilates upwards and anchor (0, 1) dilates downwards, is there an explanation for that? I understand the anchor as the point in the kernel that should match a white cell in the given mask (binary image) – Kasparov92 Jun 20 '20 at 11:33