python - 量化单个图像中不规则形状的最长轴和宽度

标签 python numpy opencv matplotlib image-processing

原始问题

我有大约 80-100 张图像,例如 (A)。每幅图像都由在 ImageJ 中标记轮廓后用黑色填充的形状组成。我需要提取每个单独的形状,如 (B) 中所示。然后我需要找到最长轴的宽度,如 (C) 中所示。

enter image description here

然后我需要计算黑色形状内规则点处的所有可能宽度,并返回包含这些值的 .csv 文件。

我一直在手动执行此操作,必须有一种更快的方法来执行此操作。知道我该怎么做吗?

部分解决方案按照 Epsi 的回答

import matplotlib.pyplot as plt
import cv2
import numpy as np

image = cv2.imread("Desktop/Analysis/NormalCol0.tif")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh_img = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours, find rotated rectangle, obtain four verticies, and draw 
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

lengths = []

for i in contours:

    x_y,width_height,angle_of_rotation = cv2.minAreaRect(i)
    Height = print(width_height[1])
    rect = cv2.minAreaRect(i)
    box = np.int0(cv2.boxPoints(rect))
    image_contours = np.zeros(image.shape)

    # Draw the contours on the empty image
    cv2.drawContours(image, [box], 0, (36,255,12), 3)
    # OR:
    # cv2.polylines(image, [box], True, (36,255,12), 3)

    plt.imshow(image)
    
cv2.imwrite(output, image)

输出:

4031.0
20.877727508544922
51.598445892333984
23.852108001708984
21.0
21.21320343017578
19.677398681640625
43.0

我能够得到每个形状的长度。 接下来我需要弄清楚如何在沿形状长度的规则点处获取形状的宽度

enter image description here

最佳答案

由于我不太擅长 python,所以我不会发布代码,但会发布解释和文档的链接。

我的做法如下:

  1. 反转图像,使所有白色变为黑色,黑色变为白色。 https://www.delftstack.com/howto/python/opencv-invert-image/#invert-images-using-numpy.invert-method-in-python

  2. 使用 findContours 查找所有(当前)白色轮廓。 https://pythonexamples.org/python-opencv-cv2-find-contours-in-image/

  3. 使用 minAreaRect 在轮廓周围创建边界框,其定位方式使框的面积尽可能小。 https://theailearner.com/tag/cv2-minarearect/

  4. 从创建的边界框中,取最长的边,这将代表轮廓的长度。

  5. 您还可以从边界框获取旋转角度

关于python - 量化单个图像中不规则形状的最长轴和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71854813/

相关文章:

python - 如何使 itertools 组合 'increase' 均匀?

python - Numpy 如何在矢量化中排除数组?

python - 计算轮廓上特定部分/边/线的斜率、长度和角度?

python - pandas:选择行 - 基于列表 - 具有重复行标签的 DF

python - 如何使用 confluence-kafka-python 删除主题

python - urllib progresshook 不准确?

opencv - 如何找到文本字段的边线

python - 为数组中的 nan 和 inf 值创建掩码

python - 读入格式化行以填充数组

python - 如何使用 OpenCV 获得金属光泽物体的轮廓