python - 在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)
#########################################################
谢谢
解决方案
我尝试以不同的方式执行此操作 - 使用与我为其他答案修剪的相同图像。这次我将每个像素计算为与原点的距离的平方,然后通过将输入图像中的所有黑色像素设置为一个大数字来使它们无法成为最近的像素。然后我在数组中找到最小的数字。
#!/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
推荐阅读
- excel - 当它应该从中提取的列中有数据时,我的 VLookup 怎么会返回 0
- javascript - 单击后松开焦点并专注于 TAB 键
- php - 是否可以使用 symfony 表单从请求创建多个实体?
- reactjs - 如何将 className 添加到 EasyUI 反应组件
- spring-boot - Prometheus 指标与微米指标(春季 2)
- python - Django CORS ORIGIN WHITELIST 和 ALLOWED_HOST 没有过滤任何东西
- javascript - 如何使用 JavaScript 将名称属性分配给动态选择选项
- android - 如何在 react-native webview 中实现 web 共享 api 和推送通知?
- sql-server - SQL server 中的函数名不明确
- android - 未收到推送通知:com.google.android.gcm.server.InvalidRequestException:HTTP 状态代码:400