使用“冲浪和透视变换”获取图像相对于基本图像的方向

时间:2017-07-25 05:51:26

标签: python python-2.7 opencv numpy image-processing

在模块del5.py

import cv2
import numpy as np

base_img = cv2.imread("/tmp/a/1.jpg")
test_img = cv2.imread("/tmp/a/1_1.jpg")

surf = cv2.xfeatures2d.SURF_create()

base_keyPoints,base_descriptors=surf.detectAndCompute(base_img,None)
test_keyPoints,test_descriptors=surf.detectAndCompute(test_img,None)

bf = cv2.BFMatcher()

matches = bf.knnMatch(base_descriptors, test_descriptors,k=2)#, k=2)

goodMatches = []

for m, n in matches:
    if m.distance < 0.7 * n.distance:
        goodMatches.append(m)

print len(goodMatches)

sourcePoints=np.float32([base_keyPoints[m.queryIdx].pt for m in goodMatches])
destinationPoints=np.float32([test_keyPoints[m.trainIdx].pt for m in goodMatches ])

print len(sourcePoints)
print len(destinationPoints)

sourcePoints = np.float32([[c[0],c[1] ]for c in sourcePoints])
destinationPoints = np.float32([[c[0],c[1] ]for c in destinationPoints])

_m = cv2.getPerspectiveTransform(sourcePoints, destinationPoints)

我正在使用python 2.7和OpenCV 3.我必须使用相同的图像但测试图像相对于基本图像旋转90度

在上面的代码中,我试图获得一个完美的测试视图(旋转图像),就像基本图像一样,我的算法步骤是:

  1. 读取两个图像(基础和测试)
  2. 创建冲浪
  3. 获取两个图片的功能
  4. 提取好的功能
  5. 获取两个图像的特征点(源点和目标点)
  6. 获取透视变换并对图像执行扭曲透视以获得完美视图
  7. 但是当我尝试获取透视图时,我收到了错误

    输出:

    > 4116
    > 4116 
    > 4116 
    > OpenCV Error: Assertion failed (src.checkVector(2,
    > CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4) in
    > getPerspectiveTransform, file
    > /opt/opencv/modules/imgproc/src/imgwarp.cpp, line 7135 Traceback (most
    > recent call last):   File "del5.py", line 41, in <module>
    >     _m = cv2.getPerspectiveTransform(sourcePoints, destinationPoints) cv2.error: /opt/opencv/modules/imgproc/src/imgwarp.cpp:7135: error:
    > (-215) src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F)
    > == 4 in function getPerspectiveTransform
    

1 个答案:

答案 0 :(得分:1)

在getPerspectiveTransform函数中,您只需传递四个点。 你正试图通过一个清单。

//In your code change this line to this.
_m = cv2.getPerspectiveTransform(sourcePoints, destinationPoints)

//Change into this one.
_m = cv2.getPerspectiveTransform(sourcePoints[0:4], destinationPoints[0:4])

对于透视变换,您需要一个3x3变换矩阵。即使在转换之后,直线仍将保持笔直。要找到此变换矩阵,输入图像上需要4个点,输出图像上需要相应的点。在这4个点中,其中3个不应该共线。转换矩阵可以通过函数cv2.getPerspectiveTransform找到。然后将cv2.warpPerspective应用于此3x3转换矩阵。

根据OpenCV文档Perspective Transformation