簡體   English   中英

OpenCV 查找輪廓的中線 [Python]

[英]OpenCV Find a middle line of a contour [Python]

在我的圖像處理項目中,我已經使用cv.findContours函數獲得了一個蒙版圖像(黑白圖像)及其輪廓。 我現在的目標是創建一個算法,可以為這個輪廓繪制一條中線。 遮罩圖像及其輪廓如下圖所示。

蒙版圖像:

蒙面圖像

輪廓:

輪廓

在我的想象中,對於那個輪廓,我想創建一條接近水平的中線。 我用紅色手動標記了我理想的中間線。 請檢查下圖是否有我提到的紅色中線。

用中線勾勒輪廓:

帶中線的輪廓

值得注意的是,我的最終目標是找到我用黃色標記的尖端點。 如果您有其他想法可以直接找到黃色提示點,也請告訴我。 為了找到黃色尖點,我嘗試了兩種方法cv.convexHullcv.minAreaRect ,但問題是魯棒性。 我讓這兩種方法適用於一些圖像,但對於我數據集中的其他一些圖像,它們效果不佳。 因此,我認為找到中間線可能是我可以嘗試的好方法。

我相信您正在嘗試確定輪廓的重心和方向。 我們可以使用Central Moments輕松做到這一點。 更多信息在這里

下面的代碼生成這個圖 這是你想要的結果嗎?

# 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()

我現在的目標是創建一個算法,可以為這個輪廓繪制一條中線。

如果您檢測到水平線的上限和下限,則可以計算中線坐標。

例如:

在此處輸入圖片說明

中線將是:

在此處輸入圖片說明

如果將大小更改為圖像的寬度:

在此處輸入圖片說明

代碼:


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()

這是另一種方法,通過在 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()

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM