簡體   English   中英

透視變換圖像片段並變換回

[英]perspective transform image segment and transform back

我目前正在嘗試從圖像中切出感興趣的區域,根據片段中的信息進行一些計算,然后將片段轉換回原始 position 或將片段上完成的計算中的一些坐標轉換回原始圖像。

以下是一些代碼片段:

    x, y, w, h = cv2.boundingRect(localized_mask)

    p1 = [x, y + h]
    p4 = [x, y]
    p3 = [x + w, y]
    p2 = [x + w, y + h]

    w1 = int(np.linalg.norm(np.array(p2) - np.array(p3)))
    w2 = int(np.linalg.norm(np.array(p4) - np.array(p1)))
    h1 = int(np.linalg.norm(np.array(p1) - np.array(p2)))
    h2 = int(np.linalg.norm(np.array(p3) - np.array(p4)))

    maxWidth = max(w1, w2)
    maxHeight = max(h1, h2)

    neighbor_points = [p1, p2, p3, p4]
    output_poins = np.float32(
        [
            [0, 0],
            [0, maxHeight],
            [maxWidth, maxHeight],
            [maxWidth, 0],
        ]
    )

    matrix = cv2.getPerspectiveTransform(np.float32(neighbor_points), output_poins)
    result = cv2.warpPerspective(
        mask, matrix, (maxWidth, maxHeight), cv2.INTER_LINEAR
    )

    

這里有一些圖片來說明這個問題:

帶有標記RoI的原始文件:

帶有標記投資回報率的原始文件

帶有標記的轉換片段:

帶有標記的轉換片段

我嘗試使用以下代碼片段將片段轉換回原始 position:

    test2 = cv2.warpPerspective(
        result, matrix, (maxHeight, maxWidth), cv2.WARP_INVERSE_MAP
    )
    test3 = cv2.warpPerspective(
        result, matrix, (img.shape[1], img.shape[0]), cv2.WARP_INVERSE_MAP
    )

兩者都產生了具有片段形狀的黑色圖像或具有原始圖像形狀的黑色圖像。

但老實說,我對代碼片段中的白色標記更感興趣,所以我嘗試使用以下代碼片段手動轉換它們:

    inverse_matrix = cv2.invert(matrix)[1]
    inverse_left=[]
    for point in output_dict["left"]["knots"]:
        trans_point = [point.x, point.y] + [1]
        trans_point = np.float32(trans_point)

        x, y, z = np.dot(inverse_matrix, trans_point)
        new_x = np.uint8(x/z)
        new_y = np.uint8(y/z)
        inverse_left.append([new_x, new_y])       

但是我沒有考慮到圖像內 RoI 的RoI和結果坐標(左上半部分的白點)並沒有出現在我想要的位置。

在此處輸入圖像描述

有沒有人知道我做錯了什么或知道這個問題的更好解決方案? 謝謝。

終於找到了一個解決方案,它就像我想象的那樣簡單......

我首先反轉了用於獲取圖像片段的轉換矩陣,然后循環並轉換了基於片段的計算得出的每個坐標。

代碼看起來像這樣:

inv_matrix = cv2.invert(matrix)
for point in points:
   x, y = (cv2.transform(np.array([[[point.x, point.y]]]), inv_matrix[1]).squeeze())[:2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM