【问题标题】:breaking contour across image border into lines将跨图像边框的轮廓分成线条
【发布时间】:2021-05-27 21:38:30
【问题描述】:

我使用函数findContours 来查找车道的边界。但是,由于车道通常会遇到图像,因此我会得到像this 这样的多边形。我真正喜欢的是线实例,所以我想知道有没有办法将多边形分解为line instances

【问题讨论】:

    标签: opencv graphics


    【解决方案1】:

    您可以使用 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);
    

    【讨论】:

    • 非常感谢!现在我可以将轮廓分成线条。现在的问题是具有曲率的同一车道被分成多条线。我可以将它们合并在一起吗? @伊恩
    • 您可以修改 epsilon 值来更改行长。此方法还返回线的点,因此如果要将两条线合并在一起,可以删除中间点。
    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    相关资源
    最近更新 更多