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:
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!
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))