无法到达左右路边

问题描述 投票:0回答:1

我试图找到代表道路掩模(二进制图像)左右边缘的点。我尝试过使用轮廓检测,但它给出了整个图像的轮廓(包括上边缘和下边缘,已附加其图像)。

我想要的是2个数组,代表左右道路边缘的点。我得到的是一长串点(轮廓),包括道路的下部。我尝试通过从数组中删除靠近边界的那些点来过滤不必要的点,现在我剩下一个仅包含来自左右道路边缘的点的数组,但现在很难判断哪个点属于哪条路边缘(左或右)。
除此之外,我还使用了索贝尔边缘检测,但它不告诉点,只生成图像。我什至想过对索贝尔边缘检测器的输出应用轮廓检测,但这会导致一些不兼容问题。

代码:


import cv2
import numpy as np

image = cv2.imread('/home/user/Desktop/seg_output/1.jpg')

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

_, binary_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)


contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Sort contours based on their area
contours = sorted(contours, key=cv2.contourArea, reverse=True)

print("Contours: ", np.squeeze(contours[0]))
print("Contours shape: ", len(contours))

contour_image = cv2.drawContours(image.copy(), contours, 0, (0, 255, 0), 2)

print("Output Shape: ", contour_image.shape)

cv2.imshow('Contours', contour_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

输入图像: Initial Input Image

输出图像:

python opencv computer-vision contour edge-detection
1个回答
0
投票

可以获取轮廓的坐标并筛选出你想要的,代码如下:

im = cv2.imread('road.jpg')
imGray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(imGray, 127, 255, cv2.THRESH_BINARY) # thresholding
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # none approximation is better than simple in this case!
largestContour = max(contours, key=cv2.contourArea) # get largest contour
height, width = im.shape[:2] # get shape
X,Y = np.array(contours).T # unpack contour to X and Y coordinates
indicesX = np.where((largestContour[:, :, 0] > 1) & (largestContour[:, :, 0] < width-1)) # get if X higher than 1 and lower than width -1
indicesY = np.where((largestContour[:, :, 1] > 1) & (largestContour[:, :, 1] < height-1))# get if Y higher than 1 and lower than height -1
combinedIndices = np.intersect1d(indicesX[0], indicesY[0]) # intersect indices
filteredContour = largestContour[combinedIndices] # get filtered contour
imContouredWithoutFilter = cv2.drawContours(im.copy(), largestContour, -1, (255, 0, 0), 3) # draw for plot
imContouredWithFilter = cv2.drawContours(im.copy(), filteredContour, -1, (0, 255, 0), 3) # draw for plot
# plotting
fig, ax = plt.subplots(nrows = 1, ncols = 2, sharex = True, sharey = True)
ax[0].imshow(imContouredWithoutFilter)
ax[0].axis("off")
ax[1].imshow(imContouredWithFilter)
ax[1].axis("off")
plt.show()

本例中最相关的行是使用

np.where
np.intersect1d
的地方。

以下是结果(左侧未过滤,右侧已过滤):

© www.soinside.com 2019 - 2024. All rights reserved.