首页 > 解决方案 > 将图像中的红线转换为 numpy 列表

问题描述

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

在此处输入图像描述

编辑:

感谢 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")

它借助图像的中间列测量上下红线之间的像素距离。我将如何遍历所有列以确定检测到的对象和下部红线之间的两条线之间的最小距离或更好的距离?我是否正确地认为该解决方案仅考虑了中间列?

标签: pythonopencvtensorflowpython-imaging-library

解决方案


您可以首先从输入图像中分割红色以获得二进制掩码,然后假设您的红线以输入图像为中心,我们取该图像的中心列并遍历该列以找到红点位置然后简单找到以像素为单位的距离:

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


推荐阅读