python - 将图像中的红线转换为 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")
它借助图像的中间列测量上下红线之间的像素距离。我将如何遍历所有列以确定检测到的对象和下部红线之间的两条线之间的最小距离或更好的距离?我是否正确地认为该解决方案仅考虑了中间列?
解决方案
您可以首先从输入图像中分割红色以获得二进制掩码,然后假设您的红线以输入图像为中心,我们取该图像的中心列并遍历该列以找到红点位置然后简单找到以像素为单位的距离:
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:如果这不能解释什么,我很着急,请随时在评论中提问。
推荐阅读
- c# - 使用 Mailkit:“SMTP 服务器意外断开。”
- node.js - 如何避免 windows server 2016 上的 powershell 出现致命错误或未知错误
- c# - 如何将标签页动态添加到标签控件的开头
- objective-c - Square Reader SDK 上架构 armv7 的未定义符号
- reactjs - 使用 React 测试库进行测试下拉
- python - 未能在 Python 中使用 QuantLib 通货膨胀债券定价器获得正确的应计利息
- python - 如何在另一个字典的列表中打印出字典的值
- docker - 为什么docker在空目录中列出文件?
- go - 如何捕获“切片超出范围”错误并为其编写句柄
- apache - 用主域屏蔽子域