我想测量此管道中检测到的物体与地面的高度差。下方的红线应为最小高度的标记。我以为我可能会先将较低的红线转换为一个numpy列表,但是我该怎么做呢?红色圆圈用cv2.circle()函数绘制。

python - 将图像中的红线转换为numpy列表-LMLPHP

编辑:

多亏了ZdaR,我才可以解决我的问题。这是他重写为与python3配合使用的解决方案:

import cv2
import numpy as np


def get_center(arr):
    return sum(arr)/len(arr)


def get_cluster_centers(arr, tolerance):
    clusters = [[arr[0]]]

    for ele in arr[1:]:
        if abs(clusters[-1][0] - ele) < tolerance:
            clusters[-1].append(ele)
        else:
            clusters.append([ele])

    clusters_centers = map(get_center, clusters)
    return clusters_centers


img = cv2.imread("/home/artur/Desktop/0.png")

# Segment the red color
mask = cv2.inRange(img, np.array([0, 0, 255]), np.array([0, 0, 255]))

for i in mask:
    print(i)

# Let's iterate the middle column and get the distance between the two red lines.
half_width = int(mask.shape[1]/2)
middle_column = mask[:, half_width]

idx = np.where(middle_column == 255)

# Since the width of line is not 1 px so we need to cluster the pixels to get a single center value.
centers = list(get_cluster_centers(idx[0], 5))

if len(centers) == 2:
    print("Distance between lines:", centers[1] - centers[0], "px")

它借助图像的中间列来测量上下红线之间的像素距离。我如何遍历所有列以确定这两条线之间或更短的距离,检测到的物体与较低的红线之间的最小距离?我是否正确地知道此解决方案仅考虑中间列?

最佳答案

您可以先将输入图像中的红色分割成一个二进制蒙版,然后假设您的红线位于输入图像的中心,我们获取该图像的中心列并在该列上进行迭代以找到红点位置,然后简单地找到以像素为单位的距离为:

import cv2
import numpy as np


def get_center(arr):
    return sum(arr)/len(arr)


def get_cluster_centers(arr, tolerance):
    clusters = [[arr[0]]]

    for ele in arr[1:]:
        if abs(clusters[-1][0] - ele) < tolerance:
            clusters[-1].append(ele)
        else:
            clusters.append([ele])

    clusters_centers = map(get_center, clusters)
    return clusters_centers


img = cv2.imread("/home/anmol/Downloads/HK3WM.png")

# Segment the red color
mask = cv2.inRange(img, np.array([0, 0, 255]), np.array([0, 0, 255]))

# Let's iterate the middle column and get the distance between the two red lines.
half_width = mask.shape[1]/2
middle_column = mask[:, half_width]

idx = np.where(middle_column == 255)

# Since the width of line is not 1 px so we need to cluster the pixels to get a single center value.
centers = get_cluster_centers(idx[0], 5)

if len(centers) == 2:
    print "Distance between lines:", centers[1] - centers[0], "px"

PS:如果这不能解释评论中的问题,我很着急。

10-06 00:53