0

Let's say I have an image of a book cover that I want to "flatten". To do so it seems like I would need to perform 2 perspective transforms: one just for the front cover and one just for the back cover:

enter image description here

What would be the most efficient way to do this?

LaPXL8R
  • 39
  • 2
  • 11
  • Possible duplicate of [extracting a quadrilateral image to a rectangle](https://stackoverflow.com/questions/2992264/extracting-a-quadrilateral-image-to-a-rectangle) – Lev Zakharov Sep 04 '18 at 23:52
  • @LevZakharov It seems like that is for one quadrilateral section, I was wondering how it could be done for 2 sections in the same image – LaPXL8R Sep 04 '18 at 23:59
  • 1
    You can detect rectangles separately, transform them ("flatten") and than combine. – Lev Zakharov Sep 05 '18 at 00:04

1 Answers1

2

Using a 600x600 pixel image homograpy-test.jpg: enter image description here

import cv2
import numpy as np

#load image
img = cv2.imread('homography-test.jpg', cv2.IMREAD_COLOR)

#corners of book covers (before)
frontCoverPtsBefore = np.array([[32, 48], [279, 136], [247, 430], [39, 281]], dtype="float32")
backCoverPtsBefore = np.array([[279, 136], [474, 36], [463, 316], [247, 430]], dtype="float32")

#corners of book covers (after)
frontCoverPtsAfter = np.array([[0, 0], [299, 0], [299, 599], [0, 599]], dtype="float32")
backCoverPtsAfter = np.array([[300, 0], [599, 0], [599, 599], [300, 599]], dtype="float32")

#get the transformation matrices for both covers
M_front = cv2.getPerspectiveTransform(frontCoverPtsBefore, frontCoverPtsAfter)
M_back = cv2.getPerspectiveTransform(backCoverPtsBefore, backCoverPtsAfter)

#warpPerspective both images
img_front = cv2.warpPerspective(img, M_front, (600, 600))
img_back = cv2.warpPerspective(img, M_back, (600, 600))

#copy half of the warped back cover into the warped front cover
np.copyto(img_front[:, 300:, :], img_back[:, 300:, :])

#display before and after
cv2.imshow('img', img)
cv2.imshow('img_front', img_front)
cv2.waitKey(0)
cv2.destroyAllWindows()

Before and After: enter image description here

LaPXL8R
  • 39
  • 2
  • 11
  • 1
    very nice answer. Very good sample image. I would've used (warped) masks for the copyTo part, though. – Micka Sep 05 '18 at 06:06