如何强制 approxPolyDP() 仅返回最好的 4 个角?- OpenCV 2.4.2

Zah*_*dar 6 c++ opencv artificial-intelligence image-processing

好吧,这个问题说明了一切

我有一些轮廓,我想从中得到最好的四边形

Ale*_*ruk 6

我相信您可以对值执行二分搜索epsilon以找到最佳简化。

代码:

def simplify_contour(contour, n_corners=4):
    '''
    Binary searches best `epsilon` value to force contour 
        approximation contain exactly `n_corners` points.

    :param contour: OpenCV2 contour.
    :param n_corners: Number of corners (points) the contour must contain.

    :returns: Simplified contour in successful case. Otherwise returns initial contour.
    '''
    n_iter, max_iter = 0, 100
    lb, ub = 0., 1.

    while True:
        n_iter += 1
        if n_iter > max_iter:
            return contour

        k = (lb + ub)/2.
        eps = k*cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, eps, True)

        if len(approx) > n_corners:
            lb = (lb + ub)/2.
        elif len(approx) < n_corners:
            ub = (lb + ub)/2.
        else:
            return approx
Run Code Online (Sandbox Code Playgroud)


Ral*_*zky 3

epsilon由于点数随着 的减少而增加,因此您必须使用嵌套间隔的方法来找到合适的值epsion。但有可能无法达到 4 个角点的值,因为在特定的 epsilon 值下,点的数量可能从 3 跳到 5。

\n\n

如果您想排除这种情况,您可能需要自己实现 Ramer\xe2\x80\x93Douglas\xe2\x80\x93Peucker 算法并对其进行修改,以便返回给定数量的点。(顺便说一句,您要求的是“最佳”4 个角。您必须指定最佳的含义。approxPolyDp()并不要求最佳解决方案!)

\n\n

除此之外,我看不出有什么办法可以强行approxPolyDP()返还4分。

\n