Computing distance maps
In this recipe, you will learn how to compute the distance to the closest non-zero pixels from each image pixel. This functionality can be used to perform image processing in an adaptive way, for instance, for blurring an image with different strengths, depending on the distance to the closest edge.
Getting ready
Install the OpenCV 3.x Python API package and the matplotlib
package.
How to do it...
- Import the modules:
import cv2 import numpy as np import matplotlib.pyplot as plt
- Draw a test image—a black circle (without filling) on a white background:
image = np.full((480, 640), 255, np.uint8) cv2.circle(image, (320, 240), 100, 0)
- Compute the distance from every point to the circle:
distmap = cv2.distanceTransform(image, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
- Visualize the results:
plt.figure() plt.imshow(distmap, cmap='gray') plt.show()
How it works...
Distance maps can be calculated using the OpenCV cv2.distanceTransform
function. It calculates the specified type of distance (cv2...