用python在二进制numpy数组中查找到1的距离

2024-10-03 11:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个机器人项目中,我使用超声波作为视觉。根据边缘检测算法,我生成了一个二进制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)
#########################################################

enter image description here

谢谢


Tags: importnumpybandnpmaskresultwherelabel
2条回答

我试着用另一种方式来做这件事——使用我为另一个答案修剪的相同图像。这一次,我将每个像素计算为距原点距离的平方,然后将输入图像中的所有黑色像素设置为一个大数字,使其不适合作为最近的像素。然后我找到数组中的最小数

#!/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

我修剪你的图像如下-请不要张贴带有轴和标签的图像,如果人们需要处理它们

enter image description here

然后利用Scipy的cdist()函数。所以,首先生成图像中所有白色像素的列表,然后计算从左上角的原点到列表中每个像素的距离。然后找到最小的一个

#!/usr/bin/env python3

import numpy as np
from PIL import Image
from scipy.spatial.distance import cdist

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

# Get coordinates of white pixels
whites = np.where(na>127)

# Get distance from [0,0] to each white pixel
distances = cdist([(0,0)],np.transpose(whites))

# Index of nearest
ind = distances.argmin()

# Distance of nearest
d = distances[0,ind]

# Coords of nearest
x, y = whites[0][ind], whites[1][ind]

print(f'distance [{x},{y}] = {d}')

样本输出

distance [159,248] = 294.5929394944828

如果我画一个以原点为中心半径=294的红色圆圈和一个以x,y坐标为中心的蓝色圆圈:

enter image description here

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

相关问题 更多 >