测量两点之间的距离

时间:2018-07-21 16:00:35

标签: image-processing scikit-image

我想使用 scikit-image 测量两点之间的距离。这是图片: enter image description here

在上面的照片中,我想测量红点黑点之间的距离。度量单位对我来说无关紧要,因为我想在一天结束前归一化距离。知道我该怎么做吗? 谢谢

1 个答案:

答案 0 :(得分:0)

您可以通过以下逐步过程来完成工作:

  • 计算每个像素到红色和黑色的距离。
  • 使用适当的threshold进行二分类。
  • 进行形态学闭合。
  • 确定所得斑点的质心坐标。
  • 计算质心之间的距离。

希望下面的代码能使您走上正确的轨道:

import numpy as np
from skimage import io
from skimage.morphology import closing
from skimage.measure import regionprops
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch

img = io.imread('https://i.stack.imgur.com/vbOmy.jpg')

red = [255, 0, 0]
black = [0, 0, 0]

threshold = 10

dist_from_red = np.linalg.norm(img - red, axis=-1)
dist_from_black = np.linalg.norm(img - black, axis=-1)

red_blob = closing(dist_from_red < threshold)
black_blob = closing(dist_from_black < threshold)

labels = np.zeros(shape=img.shape[:2], dtype=np.ubyte)
labels[black_blob] = 1
labels[red_blob] = 2

blobs = regionprops(labels)

center_0 = np.asarray(blobs[0].centroid[::-1])
center_1 = np.asarray(blobs[1].centroid[::-1])

dist = np.linalg.norm(center_0 - center_1)

演示

fig, ax = plt.subplots(1, 1)
ax.imshow(img)

con = ConnectionPatch(xyA=center_0, xyB=center_1, 
                      coordsA='data', arrowstyle="-|>", ec='yellow')
ax.add_artist(con)

plt.annotate('Distance = {:.2f}'.format(dist), 
             xy=(center_0 + center_1)/2, xycoords='data',
             xytext=(0.5, 0.7), textcoords='figure fraction', color='blue', 
             arrowprops=dict(arrowstyle="->", color='blue'))
plt.show(fig)

Annotated image

相关问题