warpPerspective(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst @brief Applies a perspective transformation to an image. The function warpPerspective transforms the source image using the specified matrix: \f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert and then put in the formula above instead of M. The function cannot operate in-place. @param src input image. @param dst output image that has the size dsize and the same type as src . @param M \f$3\times 3\f$ transformation matrix. @param dsize size of the output image. @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( \f$\texttt{dst}\rightarrow\texttt{src}\f$ ). @param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). @param borderValue value used in case of a constant border; by default, it equals 0. @sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform | warpPerspective(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) -> dst @brief 对图像应用透视变换。 函数 warpPerspective 使用指定的矩阵转换源图像: 当flag #WARP_INVERSE_MAP 被设置时。 否则,变换先用invert取反,然后代入上面的公式而不是M。该函数不能就地操作。 @param src 输入图像。 @param dst 输出图像,其大小为 dsize 且类型与 src 相同。 @param M \f$3\times 3\f$ 变换矩阵。 @param dsize 输出图像的大小。 @param 标记插值方法(#INTER_LINEAR 或 #INTER_NEAREST)和可选标记 #WARP_INVERSE_MAP 的组合,将 M 设置为逆变换。 @param borderMode 像素外推方法(#BORDER_CONSTANT 或 #BORDER_REPLICATE)。 @param borderValue 用于恒定边框的值;默认情况下,它等于 0。 @sa warpAffine、调整大小、重新映射、getRectSubPix、perspectiveTransform |
函数原理:
透视变换(Perspective Transformation)是将图片投影到一个新的视平面(Viewing Plane),也称作投影映射(Projective Mapping)。通用的变换公式为:
u,v是原始图片左边,对应得到变换后的图片坐标x,y,其中。
变换矩阵可以拆成4部分,表示线性变换,比如scaling,shearing和ratotion。用于平移,产生透视变换。所以可以理解成仿射等是透视变换的特殊形式。经过透视变换之后的图片通常不是平行四边形(除非映射视平面和原来平面平行的情况)。
重写之前的变换公式可以得到:
所以,已知变换对应的几个点就可以求取变换公式。反之,特定的变换公式也能新的变换后的图片。简单的看一个正方形到四边形的变换:
变换的4组对应点可以表示成:
根据变换公式得到:
定义几个辅助变量:
都为0时变换平面与原来是平行的,可以得到:
不为0时,得到:
求解出的变换矩阵就可以将一个正方形变换到四边形。反之,四边形变换到正方形也是一样的。于是,我们通过两次变换:四边形变换到正方形+正方形变换到四边形就可以将任意一个四边形变换到另一个四边形。
参考链接: