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

使用OpenCV(CV2)绘制弯曲物体中心线并测量蠕虫长度与面积

弯曲物体(蠕虫)的中心线绘制与自动化测量

需求与现状

  • 实现数百张图片的自动化处理,替代手动测量:为弯曲物体(以蠕虫为例)绘制中心线以计算长度,同时测量其面积。
  • 已完成:通过Python与OpenCV成功提取物体轮廓。
  • 待解决问题:绘制中心线以计算长度的环节未得到理想结果,尝试过凸包、骨架提取、polyDP方法均无效。

现有原型代码

import numpy as np
import cv2
import os

draw_windows = True  ## change to False for no windows only calc


def calc_values(filename):
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)
    ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

    drawWindow('thresh', thresh)

    edged = cv2.Canny(gray, 50, 100)
    edged = cv2.dilate(edged, None, iterations=1)
    edged = cv2.erode(edged, None, iterations=1)

    drawWindow('edged', edged)


    contours, _ = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    # Assume the largest contour corresponds to the worm
    if contours:
        largest_contour = max(contours, key=cv2.contourArea)

        # Draw the contour on the original image
        image_with_contour = cv2.cvtColor(edged, cv2.COLOR_GRAY2BGR)
        cv2.drawContours(image_with_contour, [largest_contour], -1, (0, 255, 0), 2)
        cv2.drawContours(image_with_contour, contours, -1, color=(255, 255, 255), thickness=cv2.FILLED)

        # Display the original image with the detected contour
        drawWindow('Worm with Contour', image_with_contour)


def drawWindow(window_name, image):
    if draw_windows:
        cv2.imshow(window_name, image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


def main():
    directory = "input"
    for filename in os.listdir(directory):
        file = os.path.join(directory, filename)
        calc_values(file)


if __name__ == "__main__":
    main()

(注:代码为快速原型,质量有待优化)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:11:37