• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C#使用opencv截取旋转矩形区域图像的实现示例

c# 搞代码 4年前 (2022-01-09) 20次浏览 已收录 0个评论
文章目录[隐藏]

前言:最近在工程中需要用到截取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截取内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C#使用opencv截取旋转矩形区域图像的实现示例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址