opencv查找从特定点到图像中每个像素的距离?

时间:2020-08-09 19:14:20

标签: numpy opencv

我有黑白图像,我想找到每个白色像素到某个点的欧几里德距离。

def remove_pixel(img,point,distance ):
  rimg=np.copy(img)
  for i in range(rimg.shape[0]):
    for j in range(rimg.shape[1]):
      if rimg[i,j]==1 and distance((i,j),point)<distance:
        rimg[i,j]=0
  return rimg

如何不使用循环就可以做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以通过使用numpy.indicesnumpy.where来向量化函数,如下所示:

import numpy as np

def remove_pixel(img, point, distance):
    rows, cols = np.indices(img.shape)
    mask = (rows - point[0])**2 + (cols - point[1])**2 < distance**2
    return np.where(mask, 0, img)

演示

In [36]: from skimage.data import checkerboard

In [37]: import matplotlib.pyplot as plt

In [38]: img = checkerboard()

In [39]: out = remove_pixel(img, [75, 75], 50)

In [40]: fig, (ax0, ax1) = plt.subplots(1, 2)
    ...: ax0.imshow(img, cmap='gray')
    ...: ax0.axis('off')
    ...: ax0.set_title('img')
    ...: ax1.imshow(out, cmap='gray')
    ...: ax1.axis('off')
    ...: ax1.set_title('out')
    ...: plt.show(fig)

Results