如何使矩形对象变形以适合其较大的边框

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

给出此图像:

“

我想使其旋转并拉伸以完全适合边界框,而最大矩形框的外部没有空白。它也应该考虑更糟的透视情况,就像我稍后列出的链接中一样。

基本上,虽然它并不明显,但将矩形稍微旋转了一点,我想修复该变形。

但是,尝试检索轮廓的四个点时出现错误。我已经确定并利用轮廓逼近来隔离并仅获得相关外观的轮廓,并且您可以在图像中看到它是成功的,尽管我不能在其上使用透视扭曲。

我已经在这里尝试了链接:

然后跟随它们,仅进行了较小的修改(例如,不先缩小图像然后再放大图像)和不同的输入图像。

[那里的读者遇到类似的错误,但是作者只是说要使用轮廓逼近。我做到了,但仍然收到相同的错误。

我已经检索了轮廓(连同它的边界框,是前面显示的图像,并使用此代码尝试了迫切变形:]

def warp_perspective(cnt):
    # reshape cnt to get tl, tr, br, bl points
    pts = cnt.reshape(4, 2)
    rect = np.zeros((4, 2), dtype="float32")

    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]
    rect[2] = pts[np.argmin(s)]

    diff = np.diff(pts, axis=1)
    rect[1] = pts[np.argmin(diff)]
    rect[2] = pts[np.argmax(diff)]

    # solve for the width of the image
    (tl, tr, br, bl) = rect
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))

    # solve for the height of the image
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))

    # get the final dimensions
    maxWidth = max(int(widthA), int(widthB))
    maxHeight = max(int(heightA), int(heightB))

    # construct the dst image
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype="float32")

    # calculate perspective transform matrix
    # warp the perspective
    M = cv2.getPerspectiveTransform(rect, dst)
    warp = cv2.warpPerspective(orig, M, (maxWidth, maxHeight))

    cv2.imshow("warped", warp)

    return warp

该功能接受cnt作为单个轮廓。

运行时,我遇到了我之前提到的错误:

in warp_perspective
    pts = cnt.reshape(4, 2)
ValueError: cannot reshape array of size 2090 into shape (4,2)

我一点都不明白。我已经成功隔离并检索了正确的轮廓和边界框,而我所做的唯一不同就是跳过了缩小比例。.

给出该图像:我想使其旋转并拉伸以完全适合边界框,而最大矩形框的外部没有空白。还应该说明...

python image opencv image-processing contour
1个回答
1
投票

尝试这种方法:

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