8

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!

1 Answer 1

12

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)
3
  • 2
    Thanks that definitely isn't clear to me from the documentation and every other time this question has been asked, people focused on the floating point part of the error. Dec 21, 2014 at 16:00
  • 4
    Why the input of perspectiveTransform() is src[None, :, :] not just src? Does each element must be an 2D matrix instead of a vector? @user1549912
    – nn0p
    Oct 5, 2015 at 17:00
  • @nn0p see here answers.opencv.org/question/252/…
    – Dale
    Jul 9, 2019 at 17:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.