Reputation: 1384
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!
Upvotes: 0
Views: 1260
Reputation: 1
To answer OP's second part of the 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?
The anchor point is the point that will be replaced by the BRIGHTEST pixel in the kernel, in the dilation operation. opencv 2D coordinate (x, y): origin is top left, x is to the right and y is down. The kernel you set is of shape (1, 2), which means it is 1 pixel wide and 2 pixels in height:
Upvotes: 0
Reputation: 2018
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))
Upvotes: 1