Kasparov92
Kasparov92

Reputation: 1384

Set Dilation Kernel Anchor

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!

Upvotes: 0

Views: 1260

Answers (2)

user25198148
user25198148

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:

  • when anchor is (0, 0), the anchor point is the top pixel in the kernel. Which means that if the pixel (0, 1) below is white, the anchor point is gonna be dilated to white => anchor (0, 0) will dilate UPWARDS
  • when anchor is (0, 1), the anchor point is the bottom pixel in the kernel. Which means that if the pixel (0, 0) above is white, the anchor point is gonna be dilated to white => anchor (0, 1) will dilate DOWNWARDS

Upvotes: 0

Alex Alex
Alex Alex

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

Related Questions