首页 > 解决方案 > 在python中查找二进制numpy数组中的距离

问题描述

对于机器人项目,我使用超声波作为视觉。从边缘检测算法中,我生成了一个二进制 numpy 数组。现在,我不确定计算到物体距离的最经济有效的方法是什么。假设我想计算从 1 到左上角的最短距离?是否可以使用“np.where”和“dst = numpy.linalg.norm()”?

import numpy as np
from scipy import ndimage
from PIL import Image


Max_filtrated = np.where(result>np.amax(result)*0.8,0,result)
Band_filtrated = np.where(Max_filtrated>np.amax(Max_filtrated)*0.11, 
1,0)

####### Define connected region and remove noise ########
mask = Band_filtrated> Band_filtrated.mean()
label_im, nb_labels = ndimage.label(mask)
sizes = ndimage.sum(mask, label_im, range(nb_labels + 1))
mean_vals = ndimage.sum(im, label_im, range(1, nb_labels + 1))
mask_size = sizes < 500
remove_pixel = mask_size[label_im]
label_im[remove_pixel] = 0
Ferdig= np.where(label_im>np.amax(label_im)*0.1,1,0)
#########################################################

在此处输入图像描述

谢谢

标签: pythonnumpy

解决方案


我尝试以不同的方式执行此操作 - 使用与我为其他答案修剪的相同图像。这次我将每个像素计算为与原点的距离的平方,然后通过将输入图像中的所有黑色像素设置为一个大数字来使它们无法成为最近的像素。然后我在数组中找到最小的数字。

#!/usr/bin/env python3

import sys
import numpy as np
from PIL import Image

# Open image in greyscale and make into Numpy array
im = Image.open('curve.png').convert('L')
na = np.array(im)

# Make grid where every pixel is the squared distance from origin - no need to sqrt()
# This could be done outside main loop, btw
x,y = np.indices(na.shape)
dist = x*x + y*y

# Make all black pixels inelligible to be nearest
dist[np.where(na<128)] = sys.maxsize

# Find cell with smallest value, i.e. smallest distance
resultY, resultX = np.unravel_index(dist.argmin(), dist.shape)

print(f'Coordinates: [{resultY},{resultX}]')

样本输出

Coordinates: [159,248]

关键词:Python,图像处理,最近的白色像素,最近的黑色像素,最近的前景像素,最近的背景像素,Numpy


推荐阅读