OpenCV:了解 warpPerspective / 透视变换

OpenCV: Understanding warpPerspective / perspective transform

我给自己做了一个小例子来玩玩OpenCVs wrapPerspective,但是输出并不完全符合我的预期。

我的输入是一个 45° 角的条。我想对其进行转换,使其垂直对齐/呈 90° 角。没问题。然而,我不明白的是,实际目的地点周围的一切都是黑色的。我不明白这一点的原因是,实际上只有转换矩阵被传递给 wrapPerspective 函数,而不是目标点本身。所以我的预期输出将是一个 90° 角的条形,并且它周围的大部分是黄色而不是黑色。我的推理错误在哪里?

# helper function
def showImage(img, title):
    fig = plt.figure()
    plt.suptitle(title)
    plt.imshow(img)


# read and show test image
img = mpimg.imread('test_transform.jpg')
showImage(img, "input image")


# source points
top_left = [194,430]
top_right = [521,103]
bottom_right = [549,131]
bottom_left = [222,458]
pts = np.array([bottom_left,bottom_right,top_right,top_left])


# target points
y_off = 400; # y offset
top_left_dst = [top_left[0], top_left[1] - y_off]
top_right_dst = [top_left_dst[0] + 39.6, top_left_dst[1]]
bottom_right_dst = [top_right_dst[0], top_right_dst[1] + 462.4]
bottom_left_dst = [top_left_dst[0], bottom_right_dst[1]]
dst_pts = np.array([bottom_left_dst, bottom_right_dst, top_right_dst, top_left_dst])

# generate a preview to show where the warped bar would end up
preview=np.copy(img)
cv2.polylines(preview,np.int32([dst_pts]),True,(0,0,255), 5)
cv2.polylines(preview,np.int32([pts]),True,(255,0,255), 1)
showImage(preview, "preview")


# calculate transformation matrix
pts = np.float32(pts.tolist())
dst_pts = np.float32(dst_pts.tolist())
M = cv2.getPerspectiveTransform(pts, dst_pts)

# wrap image and draw the resulting image
image_size = (img.shape[1], img.shape[0])
warped = cv2.warpPerspective(img, M, dsize = image_size, flags = cv2.INTER_LINEAR)
showImage(warped, "warped")

使用此代码的结果是:

这是我的输入图像 test_transform.jpg: 这是添加了坐标的同一图像:

根据要求,这里是转换矩阵:

[[  6.05504680e-02  -6.05504680e-02   2.08289910e+02]
 [  8.25714275e+00   8.25714275e+00  -5.12245707e+03]
 [  2.16840434e-18   3.03576608e-18   1.00000000e+00]]

您在数组中的排序或其位置可能有问题。检查这个转换后的图像: dst_pts 数组是:np.array([[196,492],[233,494],[234,32],[196,34]]),这或多或少像蓝色预览图像中的矩形。(我自己制作坐标以确保它们是正确的) 注意:您的源点和目标点的顺序应该正确