有没有办法在 OpenCV/skimage 中获取浮点坐标的轮廓属性?

Is there a way to get contour properties in OpenCV/skimage for floating point coordinates?

我在 Matplotlib 中创建了等高线图,我需要进一步分析它们是否是闭合曲线,然后查看细胞结构的面积、凸度、坚固度等。在 Matplotlib 中,它们是 LineCollectionPath.

类型

在 OpenCV 中,我无法将 float 数组传递给 cv2.contourArea 或类似函数。另一方面,转换为 uint8 坐标会丢失嵌套结构等重要数据。在这种情况下,我需要到达内部嵌套的凸轮廓。

是否有任何选项可以在 Python 中查找面积、凸包、边界矩形等信息?

我可以放大图片,但我担心图片会莫名其妙地歪斜。

例如:附有浮点数和整数坐标的图像。

我假设,您可以完全控制 Matplotlib 部分。因此,让我们尝试从那里获取图像,您可以轻松地将其用于 OpenCV 的进一步图像处理。

我们从一些常见的 contour 情节开始,如您的问题所示:

您可以设置levels参数来获取单个等高线级别。这有助于单独处理多个级别。下面重点介绍levels=[1.75](最里面的绿色椭圆)。稍后,您可以简单地遍历所有需要的级别,并执行您的分析。

对于我们的自定义等高线图,我们将设置一个固定的 x, y 域,例如 [-3, 3] x [-2, 2],使用 xlim and ylim. So, we have known dimensions for the actual canvas. We get rid of the axes using axis('off'), and the margins around the canvas using tight_layout(pad=0)。剩下的就是全尺寸的plaincanvas(图形尺寸调整为(10, 5),颜色自动调整为层数):

现在,我们将 canvas 保存到某个 NumPy 数组中,参见。 this Q&A。从那里,我们可以执行任何 OpenCV 操作。为了找到这个级别轮廓的组合面积,我们可能会对灰度图像进行阈值处理,找到所有轮廓,并使用 cv2.contourArea 计算它们的面积。我们将这些区域相加,得到以像素为单位的整个区域。从已知的 canvas 维度,我们知道整个 canvas 区域的“单位”,从图像维度,我们知道整个 canvas 区域的像素。因此,我们只需要将整个轮廓区域(以像素为单位)除以整个 canvas 区域(以像素为单位),然后乘以整个 canvas 区域(以“单位”为单位)。

这就是全部代码:

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

# Generate some data for some contour plot
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X + 1.5)**2 - Y**2)
Z2 = np.exp(-(X - 1.5)**2 - Y**2)
Z = (Z1 + Z2) * 2

# Custom contour plot
x_min, x_max = -3, 3
y_min, y_max = -2, 2
fig = plt.figure(2, figsize=(10, 5))    # Set large figure size
plt.contour(X, Y, Z, levels=[1.75])     # Set single levels if needed
plt.xlim([x_min, x_max])                # Explicitly set x limits
plt.ylim([y_min, y_max])                # Explicitly set y limits
plt.axis('off')                         # No axes shown at all
plt.tight_layout(pad=0)                 # No margins at all

# Get figure's canvas as NumPy array, cf. 
fig.canvas.draw()
img = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))

# Grayscale, and threshold image
mask = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
mask = cv2.threshold(mask, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1]

# Find contours, calculate areas (pixels), sum to get whole area (pixels) for certain level
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
area = np.sum(np.array([cv2.contourArea(cnt) for cnt in cnts]))

# Whole area (coordinates) from canvas area (pixels), and x_min, x_max, etc.
area = area / np.prod(mask.shape[:2]) * (x_max - x_min) * (y_max - y_min)
print('Area:', area)

输出区域似乎合理:

Area: 0.861408

现在,您可以随意使用 OpenCV 进行任何图像处理了。永远记住将任何以像素为单位的结果转换为以“单位”为单位的结果。

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
PyCharm:       2021.1.1
Matplotlib:    3.4.1
NumPy:         1.20.2
OpenCV:        4.5.1