前言:最近在工程中需要用到截取RotatedRect中的图形,保存为Mat做后续处理。发现opencv文档中没有这个api,最开始想到的方案是将整张图片进行相应的旋转,然后再从中截取正矩形,但是我们要获取的是部分区域,将整张图片进行旋转会造成很多的资源浪费。所以需要自行实现一个旋转矩形的方案。
实现方法
原理是利用向量空间变换,如图
然后做一个二重循环,将j从0循环到height,i从0循环到width,就可以得到输出Mat所有像素的信息。
下面为一个截取BGR类型的Mat的RotatedRect的代码
///<Summary> ///利用向量运算截取一个RotatedRect区域 ///</Summary> ///<param name="img">类型为CV_U8C3的Mat</param> ///<param name="rotatedRect">RotatedRect</param> public static Mat sliceRotetedImg8UC3(Mat img,RotatedRect rotatedRect){ // Rect bounding=rotatedRect.BoundingRect(); Point2f[] points=rotatedRect.Points(); int topLeftIndex=0; double topLeftR=points[0].X*points[0].X+points[0].Y*points[0].Y; for(int i=1;i<4;i++){ double r=points[i]<span>本文来源gaodai#ma#com搞*代#码9网#</span>.X*points[i].X+points[i].Y*points[i].Y; if(r<topLeftR){ topLeftIndex=i; topLeftR=r; } } double x1=points[(topLeftIndex+1)%4].X-points[topLeftIndex].X,y1=points[(topLeftIndex+1)%4].Y-points[topLeftIndex].Y; double x2=points[(topLeftIndex+3)%4].X-points[topLeftIndex].X,y2=points[(topLeftIndex+3)%4].Y-points[topLeftIndex].Y; double vX1=x1,vY1=y1,vX2=x2,vY2=y2; int width=(int)Math.Sqrt(vX1*vX1+vY1*vY1),height=(int)Math.Sqrt(vX2*vX2+vY2*vY2); Mat ret=new Mat(new Size(width,height),MatType.CV_8UC3); // Console.WriteLine($"width={width},height={height}"); var indexer1=img.GetGenericIndexer<Vec3b>(); var indexer2=ret.GetGenericIndexer<Vec3b>(); for(int j=0;j<ret.Height;j++){ for(int i=0;i<ret.Width;i++){ double kx=(double)i/width,ky=(double)j/height; int x=(int)(points[topLeftIndex].X+kx*vX1+ky*vX2),y=(int)(points[topLeftIndex].Y+kx*vY1+ky*vY2); indexer2[j,i]=indexer1[y,x]; } } return ret; }
到此这篇关于C#使用opencv截取旋转矩形区域图像的文章就介绍到这了,更多相关C# opencv截取内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码!