Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Open CV perspectiveTransform()

I am trying to apply a perspective transform to a whole image using OpenCV. To do so I first calculate an initial transform based on points I have selected and then I attempt to transform the image corners and translate them to get a final optimum transform. I get the transform successfully but then applying the cv2.perspectiveTransform() function always throws up this error:

OpenCV Error: Assertion failed (scn + 1 == m.cols && (depth == CV_32F || depth == CV_64F)) in perspectiveTransform, file /tmp/opencv-PEaA0A/opencv-2.4.9/modules/core/src/matmul.cpp, line 1936

Both the numpy arrays I am providing to the function are of float64 dtype so I presume the error is from scn + 1 == m.cols. Here is a snapshot of my code:

initTransform = cv2.getPerspectiveTransform(pointsIn,pointsOut)
imgCorners = np.array([[0,0],[self.image.size/float(self.image.shape[0]),0]],dtype=np.float64)
outputCorners = cv2.perspectiveTransform(corners,initTransform) 

Thanks for your help!

like image 676
user1549912 Avatar asked Dec 20 '14 23:12

user1549912


1 Answers

Try the following code, the first argument of perspectiveTransform is a Mat object which corresponds to 3 dim array in numpy:

import cv2
import numpy as np

w, h = 512, 512
src = np.array(
    [[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], dtype=np.float32)
dst = np.array(
    [[300, 350], [800, 300], [900, 923], [161, 923]], dtype=np.float32)

m = cv2.getPerspectiveTransform(src, dst)
result = cv2.perspectiveTransform(src[None, :, :], m)
like image 110
HYRY Avatar answered Oct 15 '22 03:10

HYRY