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

标签 python opencv tensorflow python-imaging-library

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

enter image description here

编辑:

感谢 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:如果这不能解释任何问题,请随时在评论中提问,我很着急。

关于python - 将图像中的红线转换为 numpy 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52700417/

相关文章:

python - 将每列中的唯一值放入一列及其出现次数,pandas

python - 选择二维数组第二维的特定元素

python - 计算销售额的滚动(滞后和超前)差异的最佳方法是什么?

opencv - OpenCV 中的 QR 分解

python - 错误 "ImportError: DLL load failed: %1 is not a valid Win32 application"

python - 在列表中搜索一对整数的算法

python - OpenCV 不会从 MacBook Pro iSight 捕获

python - 加载以前保存的没有自定义层的模型时缺少 get_config

tensorflow - 禁用 tensorflow 训练管道中的增强

python - TF中的Keras,如何在不执行梯度下降的情况下获得每个示例的损失值?