Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Wrong perspective transform

I'm trying to do perspective transform of an image to realign the perspective. This is the input image. I want to transform the input into a rectangle.

enter image description here

The old_pts in the code refer to the points points of the quadrangle. new_pts refer to the bounding rectangle around old_pts.

I calculated perspective transform from these points using:

M = cv2.getPerspectiveTransform(old_pts, new_pts)

I transformed the original image using:

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

But I'm getting an output that is not as expected. This is the output image. I don't know what is it I'm doing wrong. Any ideas ?

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()