Below are bookhomography-example-1.jpg
and then bookhomography-example-2.jpg
from a popular OpenCV blogpost about homography.
I can do the homography and warp the image, but the h
or h[0]
do not work when I try to use cv2.perspectiveTransform(pts, h)
or cv2.perspectiveTransform(pts, h[0])
. I've also tried converting the 2D array h[0]
to a tuple of tuples, but no change. It's probably something simple, but I can't figure it out.
Error Message:
Traceback (most recent call last):
File "bookhomography stackexchange v00.py", line 36, in T_dst = cv2.perspectiveTransform(pts_dst, h) TypeError: m is not a numerical tuple
note: set False
to True
to induce failure. One of the two transform lines is the wrong direction but both fail.
import numpy as np
import matplotlib.pyplot as plt
import cv2
im_src = cv2.imread("bookhomography-example-2.jpg")
im_dst = cv2.imread("bookhomography-example-1.jpg")
im_srcrgb = cv2.cvtColor(im_src, cv2.COLOR_BGR2RGB)
im_dstrgb = cv2.cvtColor(im_dst, cv2.COLOR_BGR2RGB)
pts_src = np.float32([52, 376, 240, 528, 413, 291, 217, 266]).reshape(4, -1)
pts_dst = np.float32([56, 478, 387, 497, 376, 124, 148, 218]).reshape(4, -1)
h = cv2.findHomography(pts_src, pts_dst)
print "type(h): ", type(h)
print "len(h): ", len(h)
print "type(h[0]): ", type(h[0])
print "len(h[0]): ", len(h[0])
print "h[0].shape: ", h[0].shape
shape = im_src.shape[:2][::-1]
print h[0]
print "pts_src:"
print pts_src
print "pts_dst:"
print pts_dst
if False:
T_dst = cv2.perspectiveTransform(pts_dst, h)
T_src = cv2.perspectiveTransform(pts_src, h)
print "T_src:"
print T_src
print "T_dst:"
print T_dst
im_fin = cv2.warpPerspective(im_src, h[0], shape)
im_finrgb = cv2.cvtColor(im_fin, cv2.COLOR_BGR2RGB)
plt.figure()
plt.subplot(1, 3, 1)
plt.imshow(im_srcrgb)
x, y = pts_src.T
plt.plot(x, y, 'or', ms=8)
plt.subplot(1, 3, 2)
plt.imshow(im_dstrgb)
x, y = pts_dst.T
plt.plot(x, y, 'or', ms=8)
plt.subplot(1, 3, 3)
plt.imshow(im_finrgb)
x, y = pts_dst.T
plt.plot(x, y, 'or', ms=8)
plt.show()