OpenCV 找到等高线的中线 [Python]

OpenCV Find a middle line of a contour [Python]

在我的图像处理项目中,我已经使用cv.findContours函数获得了蒙版图像(黑白图像)及其轮廓。我现在的目标是创建一种算法,可以为该轮廓绘制一条中间线。遮罩图像及其轮廓如下图所示。

蒙版图片:

轮廓:

在我的想象中,对于那个轮廓,我想创建一条接近水平的中间线。我已经用红色手动标记了我理想的中线。请检查下图中我提到的红色中间线。

等高线与中线:

值得注意的是,我的最终目标是找到我用黄色标记的尖端点。如果大家有其他想法可以直接找到黄色提示点,也请告诉我。为了找到黄色的尖端点,我尝试了两种方法cv.convexHullcv.minAreaRect,但问题是鲁棒性。我使这两种方法适用于某些图像,但对于我数据集中的其他一些图像,它们效果不佳。因此,我认为找到中间线可能是一个很好的方法,我可以尝试。

My goal right now is to create an algorithm that can draw a middle line for this contour.

如果你检测到你的horizontal-lines的上限和下限,那么你就可以计算出middle-line坐标。

例如:

Middle-line 将是:

如果将尺寸更改为图片的宽度:

代码:


import cv2

img = cv2.imread("contour.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
(h, w) = img.shape[:2]

x1_upper = h
x1_lower = 0
x2_upper = h
x2_lower = 0
y1_upper = h
y1_lower = 0
y2_upper = h
y2_lower = 0

lines = cv2.ximgproc.createFastLineDetector().detect(gray)

for cur in lines:
    x1 = cur[0][0]
    y1 = cur[0][1]
    x2 = cur[0][2]
    y2 = cur[0][3]

    # upper-bound coords
    if y1 < y1_upper and y2 < y2_upper:
        y1_upper = y1
        y2_upper = y2
        x1_upper = x1
        x2_upper = x2
    elif y1 > y1_lower and y2 > y2_lower:
        y1_lower = y1
        y2_lower = y2
        x1_lower = x1
        x2_lower = x2


print("\n\n-lower-bound-\n")
print("({}, {}) - ({}, {})".format(x1_lower, y1_lower, x2_lower, y2_lower))
print("\n\n-upper-bound-\n")
print("({}, {}) - ({}, {})".format(x1_upper, y1_upper, x2_upper, y2_upper))

cv2.line(img, (x1_lower, y1_lower), (x2_lower, y2_lower), (0, 255, 0), 5)
cv2.line(img, (x1_upper, y1_upper), (x2_upper, y2_upper), (0, 0, 255), 5)

x1_avg = int((x1_lower + x1_upper) / 2)
y1_avg = int((y1_lower + y1_upper) / 2)
x2_avg = int((x2_lower + x2_upper) / 2)
y2_avg = int((y2_lower + y2_upper) / 2)

cv2.line(img, (0, y1_avg), (w, y2_avg), (255, 0, 0), 5)

cv2.imshow("result", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我相信您正在尝试确定轮廓的重心和方向。我们可以使用 Central Moments. More info on that here.

轻松做到这一点

下面的代码生成 this plot。这是你想要的结果吗?

# Determine contour
img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
img_bin = (img>128).astype(np.uint8)
contours, _ = cv2.findContours(img_bin, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)

# Determine center of gravity and orientation using Moments
M = cv2.moments(contours[0])
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
theta = 0.5*np.arctan2(2*M["mu11"],M["mu20"]-M["mu02"])
endx = 600 * np.cos(theta) + center[0] # linelength 600
endy = 600 * np.sin(theta) + center[1]

# Display results
plt.imshow(img_bin, cmap='gray')
plt.scatter(center[0], center[1], marker="X")
plt.plot([center[0], endx], [center[1], endy])
plt.show()

这是另一种方法,通过计算 Python/OpenCV 中对象的旋转边界框的中心线。

输入:

import cv2
import numpy as np

# load image
img = cv2.imread("blob_mask.jpg")

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold the grayscale image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# get coordinates of all non-zero pixels
# NOTE: must transpose since numpy coords are y,x and opencv uses x,y
coords = np.column_stack(np.where(thresh.transpose() > 0))

# get rotated rectangle from 
rotrect = cv2.minAreaRect(coords)
box = cv2.boxPoints(rotrect)
box = np.int0(box)
print (box)

# get center line from box
# note points are clockwise from bottom right
x1 = (box[0][0] + box[3][0]) // 2
y1 = (box[0][1] + box[3][1]) // 2
x2 = (box[1][0] + box[2][0]) // 2
y2 = (box[1][1] + box[2][1]) // 2

# draw rotated rectangle on copy of img as result
result = img.copy()
cv2.drawContours(result, [box], 0, (0,0,255), 2)
cv2.line(result, (x1,y1), (x2,y2), (255,0,0), 2)

# write result to disk
cv2.imwrite("blob_mask_rotrect.png", result)

# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果: