opencv中图片旋转的实验
参考网址:http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/imgproc/imgtrans/warp_affine/warp_affine.html
在OPENCV中实现图片旋转,首先通过getRotationMatrix2D获得旋转矩阵M,然后使用warpAffine函数结合M旋转图片。
CV_EXPORTS_W void warpAffine( const Mat& src, CV_OUT Mat& dst,
const Mat& M, Size dsize,
int flags=INTER_LINEAR,
int borderMode=BORDER_CONSTANT,
const Scalar& borderValue=Scalar());
Parameters: |
|
interpolation method:
- INTER_NEAREST - a nearest-neighbor interpolation
- INTER_LINEAR - a bilinear interpolation (used by default)
- INTER_AREA - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.
- INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood
- INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood
dst=M*src;
怎样获得M呢,OPENCV中使用另外一个函数getRotationMatrix2D来实现。
//! returns 2x3 affine transformation matrix for the planar rotation.
CV_EXPORTS_W Mat
getRotationMatrix2D( Point2f center, double angle, double scale );
Parameters: |
|
The function calculates the following matrix:
where
下面是作者的实验代码:
1 Mat img=imread("dog.jpg"); 2 Point2f p; 3 p.x=img.rows/2; 4 p.y=img.cols/2; 5 float scale=1.0; 6 Mat m=getRotationMatrix2D(p,90,scale); 7 Mat rotation; 8 Size size(img.rows*scale,img.cols*scale); 9 warpAffine(img,rotation,m,size,BORDER_CONSTANT);11 imshow("rotation",rotation); 12 imshow("src",img); 13 waitKey(0);
实验结果:
如图所示,没太明白为什么会有黑色部分出现,从图上看貌似是旋转后图片右移导致左边黑色部分的出现,由于图片大小的限制导致右边部分不能完全显示
但没搞明白原因,请大家多多指教
2014/7/3 20:15
经过尝试发现,是由于旋转中心P没有设置正确,通过对P进行变化,黑边减少图片显示接近完整,按道理旋转中心应该是(cols/2,rows/2),就算是图片尺寸奇偶数的原因,那也
只会影响一两个像素不会影响这么多,所以getRotationMatrix2D中的旋转中心与我们平时理解的旋转中心可能不太一样,不太明白其中的具体原理。希望能找到原由