Distance based weighting of pixels

Viewed 27

Assuming there is a Region of Interest in an image (a blob/object), I want to create a distance based weighting of each pixels in that image such that pixels that are further away from the blob/object are given progressively less weight, while all pixels within the ROI/blob are given a constant, highest weight. Let's assume weights range from 0-1. Is there a name for this type of distance-based weighting? How can I implement this in Python Numpy ?

1 Answers

You can consider it as a nearest neighbors problem:

  • Pixel coordinates (x, y) of your regions of interest is an index set.
  • All pixel coordinates is a query set.

Now for each pixel coordinate (x, y) on the image calculate the distance to the nearest point in the index set (ROI/blobs):

An example of ROIs / blobs: enter image description here

An example of acomputed weighted map: enter image description here

Source code:

import cv2
import numpy as np
from sklearn.neighbors import NearestNeighbors

original_image = cv2.imread("roi_mask.png", cv2.IMREAD_GRAYSCALE)

# for speeding up computations we resize the original image
image = cv2.resize(original_image, (300, 300))

h, w = image.shape[:2]
xy_grid = np.meshgrid(np.arange(w), np.arange(h))[::-1]

X_index = np.vstack(np.where(image > 100)).T.astype(np.float32)
X_query = np.dstack(xy_grid).reshape(-1, 2).astype(np.float32)

# or you can use cv2.ml.KNearest_create() or scipy.spatial.distance.cdist
knn = NearestNeighbors(n_neighbors=1)
knn.fit(X_index)
dists, _ = knn.kneighbors(X_query)

weight_map = dists.reshape(image.shape)
weight_map = cv2.normalize(weight_map, None, 0, 255, cv2.NORM_MINMAX)
weight_map = weight_map.astype(np.uint8)

weight_map = cv2.resize(weight_map, original_image.shape[:2][::-1])

image = np.hstack((original_image, weight_map))

cv2.imshow("image", image)
cv2.waitKey()
Related