【发布时间】:2021-05-27 21:38:30
【问题描述】:
我使用函数findContours 来查找车道的边界。但是,由于车道通常会遇到图像,因此我会得到像this 这样的多边形。我真正喜欢的是线实例,所以我想知道有没有办法将多边形分解为line instances。
【问题讨论】:
我使用函数findContours 来查找车道的边界。但是,由于车道通常会遇到图像,因此我会得到像this 这样的多边形。我真正喜欢的是线实例,所以我想知道有没有办法将多边形分解为line instances。
【问题讨论】:
您可以使用 approxPolyDP 将轮廓简化为更大的线条。
epsilon 值指定每条线段的最小长度。
import cv2
import numpy as np
import random
# turns a list into a tuple
def tup(arr):
return (int(arr[0]), int(arr[1]));
# load image
img = cv2.imread("rect.png");
img = img[:,1:]; # there's a weird thing on the left side
# get mask
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
mask = cv2.inRange(gray, 10, 255);
# dilate and erode to clean up lines
kernel = np.ones((3,3), np.uint8);
mask = cv2.dilate(mask, kernel, iterations = 2);
mask = cv2.erode(mask, kernel, iterations = 2);
# get contour # OpenCV 3.4, Other versions will return (countours, _)
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);
# get approximate lines
epsilon = 0.005*cv2.arcLength(contours[0],True); # epsilon is the minimum length of the line
approx = cv2.approxPolyDP(contours[0],epsilon,True);
# draw lines
for a in range(len(approx)):
color = [random.randint(0,255) for col in range(3)];
start = approx[a-1][0]; # points have an extra layer of brackets
end = approx[a][0];
cv2.line(img, tup(start), tup(end), color, 2);
# show
cv2.imshow("img", img);
cv2.waitKey(0);
【讨论】: