Welcome to DOFBOT-Ultra repository
12. Perspective Transformation
Perspective Transformation
Perspective transformation is also called projection transformation. The affine transformation we often refer to is a special case of perspective transformation. The purpose of perspective transformation is to convert objects that are straight lines in reality but may appear as slanted lines in an image back into straight lines. Perspective transformation can map a rectangle to any quadrilateral. This technique will be used later in our robot autonomous driving. Perspective transformation uses the function:
dst = cv2.warpPerspective(src, M, dsize[, flag[, borderMode[, borderValue]]])
dst: The output image after perspective transformation, dsize determines the actual output size.
src: Source image
M: 3X3 transformation matrix
dsize: Output image size.
flags: Interpolation method, default is INTER_LINEAR (bilinear interpolation). When WARP_INVERSE_MAP, it means M is an inverse transformation, enabling inverse transformation from dst to src.
borderMode: Border type. Default is BORDER_CONSTANT. When set to BORDER_TRANSPARENT, values within the target image remain unchanged, corresponding to outliers in the original image.
borderValue: Border value, default is 0. Like affine transformation, OpenCV provides a function cv2.getPerspectiveTransform() to supply the transformation matrix.
Function as follows:
matAffine = cv2.getPerspectiveTransform(matSrc, matDst)
matSrc: The four vertex coordinates of the input image.
matDst: The four vertex coordinates of the output image.
Code path:
xxxxxxxxxx~/dofbot_opencv/scripts/2.Transform/07_perspectivity.ipynb
ximport cv2import numpy as npimport matplotlib.pyplot as pltimg = cv2.imread('yahboom.jpg',1)imgInfo = img.shapeheight = imgInfo[0]width = imgInfo[1]#src 4->dst 4 (top-left, bottom-left, top-right, bottom-right)matSrc = np.float32([[200,100],[200,400],[600,100],[width-1,height-1]])matDst = np.float32([[200,200],[200,300],[500,200],[500,400]])#combinationmatAffine = cv2.getPerspectiveTransform(matSrc,matDst)# mat 1 src 2 dstdst = cv2.warpPerspective(img,matAffine,(width,height))img_bgr2rgb = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)plt.imshow(img_bgr2rgb) plt.show()