OpenCV:透视图转换意外行为

时间:2018-07-31 15:10:48

标签: python opencv computer-vision

我正在尝试对图像进行透视变换以重新排列透视。这是输入图像。我想将输入转换为矩形。

enter image description here

代码中的old_pts指向四边形的点。 new_ptsold_pts周围的边界矩形。

我使用以下几点从这些点计算出透视变换:

M = cv2.getPerspectiveTransform(old_pts, new_pts)

我使用以下方法转换了原始图像:

transformed_img = cv2.warpPerspective(new_img, M, (new_img.shape[1], new_img.shape[0]))

但是我得到的输出与预期不符。这是输出图像。我不知道我在做什么错。有什么想法吗?

enter image description here

# new_img = cv2.imread('IMG_20180731_123517_HDR.jpg')
# new_img = cv2.resize(new_img, (int(new_img.shape[2] / 10), int(new_img.shape[0] / 10)))
old_pts = np.float32([[14, 163],
                      [11, 301],
                      [242, 294],
                      [226, 166]]
                     ) 
bor = cv2.boundingRect(old_pts)  # bounding_rect
ul = [bor[0], bor[2]]  # upper left
ur = [bor[0], bor[2] + bor[3]]  # upper right
br = [bor[0] + bor[2], bor[2] + bor[3]]  # bottom right
bl = [bor[0] + bor[2], bor[2]]  # bottom left

new_pts = np.float32([ul, ur, br, bl])

# for point in new_pts:
#     cv2.circle(new_img, (point[0], point[1]), 2, (0, 0, 255), -1)
old_pts = old_pts[:, ::-1]
new_pts = new_pts[:, ::-1]
M = cv2.getPerspectiveTransform(old_pts, new_pts)
M_inv = np.linalg.inv(M)
transformed_img = cv2.warpPerspective(new_img, M, (new_img.shape[1], new_img.shape[0]))

transforemed_img = transformed_img.astype(np.uint16)
cv2.imwrite('transformed.png', transformed_img)
cv2.imshow('transformed.png', transformed_img)
cv2.imshow('original', new_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

0 个答案:

没有答案