You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图像中流体路径线的自动检测方案咨询

流体路径线长度与端点检测方案(Python实现)

针对批量流体路径线图像的长度计算与左端定位需求,以下是基于OpenCV和scikit-image的可行实现方案:

核心思路

  1. 图像预处理:统一灰度化、二值化,去除背景干扰
  2. 路径线骨架提取:将宽线条转化为单像素骨架,便于精准计算长度和定位端点
  3. 长度计算:统计骨架像素数并结合图像比例尺得到实际长度
  4. 端点定位:识别骨架的端点,筛选出最左侧的点作为目标位置
  5. 批量处理:遍历图像文件夹,导出结果至CSV文件

依赖库安装

pip install opencv-python scikit-image pandas numpy

实现代码

import cv2
import numpy as np
from skimage.morphology import skeletonize
import pandas as pd
import os

def process_flow_image(img_path, scale_factor=1.0):
    # 1. 读取图像并预处理
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 二值化(适配深色背景+浅色线条)
    _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    # 降噪(根据图像质量调整核大小)
    binary = cv2.medianBlur(binary, 3)

    # 2. 提取路径线骨架
    skeleton = skeletonize(binary / 255).astype(np.uint8) * 255

    # 3. 计算路径线长度(像素数 × 比例尺)
    pixel_length = np.sum(skeleton == 255)
    actual_length = pixel_length * scale_factor

    # 4. 定位最左侧端点
    y_coords, x_coords = np.where(skeleton == 255)
    endpoints = []
    # 筛选邻域内相邻骨架像素≤1的点(端点特征)
    for x, y in zip(x_coords, y_coords):
        neighborhood = skeleton[y-1:y+2, x-1:x+2]
        if np.sum(neighborhood == 255) <= 2:
            endpoints.append((x, y))
    # 取x坐标最小的点(最左侧)
    leftmost_point = min(endpoints, key=lambda p: p[0]) if endpoints else (0, 0)

    return {
        'filename': os.path.basename(img_path),
        'pixel_length': pixel_length,
        'actual_length': actual_length,
        'left_x': leftmost_point[0],
        'left_y': leftmost_point[1]
    }

# 批量处理入口
if __name__ == '__main__':
    image_dir = 'your_image_folder_path'  # 替换为你的图像文件夹路径
    scale_factor = 0.1  # 替换为实际比例尺(如1像素=0.1mm)
    results = []

    for img_name in os.listdir(image_dir):
        if img_name.lower().endswith(('.jpg', '.png')):
            img_path = os.path.join(image_dir, img_name)
            result = process_flow_image(img_path, scale_factor)
            results.append(result)

    # 导出结果到CSV
    df = pd.DataFrame(results)
    df.to_csv('flow_line_results.csv', index=False)

关键说明

  • 参数适配:若图像背景干扰严重,可替换二值化方法为cv2.adaptiveThreshold;降噪核大小(medianBlur的3)可根据线条粗细调整。
  • 比例尺校准:scale_factor需通过已知长度的参照物校准,确保实际长度计算准确。
  • 分支处理:若图像存在多分支线条,可先通过cv2.findContours筛选面积最大的轮廓(主路径),再提取骨架,避免干扰。

内容的提问来源于stack exchange,提问作者Suuuehgi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:06:41