需求:项目中需要从20000*20000px以上,裁剪旋转矩形(大概100*1000大小)。
PS:去掉Cv2.ImShow() 整体时间更快!
public static void OpencvCutDemo(Mat imageSource,int center_x=5000,int center_y=5000,int cut_width = 300,int cut_height=500,float cut_angle=55) { RotatedRect rect = new RotatedRect(new Point2f(center_x, center_y), new Size2f(cut_width, cut_height), cut_angle); var vertices = rect.Points(); //画原坐标线 for (int j = 0; j < 4; j++) { Cv2.Line(imageSource, (Point)vertices[j], (Point)vertices[(j + 1) % 4], new Scalar(255, 255, 0)); } //画外接矩阵线 Rect brect = rect.BoundingRect(); Cv2.Rectangle(imageSource, brect, new Scalar(255, 0, 0)); RotatedRect rect1 = new RotatedRect(new Point2f(center_x - brect.X, center_y - brect.Y), new Size2f(cut_width, cut_height), cut_angle); Rect brect1 = rect1.BoundingRect(); / * 裁剪外接矩阵,再重新计算坐标进行裁剪 * / int w = brect.X + brect.Width > imageSource.Width ? imageSource.Width - brect.X : brect.Width; int h = brect.Y + brect.Height > imageSource.Height ? imageSource.Height - brect.Y : brect.Height; var minAreaRectMat = new Mat(imageSource, new Rect(brect.Location, new Size(w, h))); Cv2.Rectangle(minAreaRectMat, brect1, new Scalar(255, 0, 255)); Cv2.ImShow("imageSource", imageSource); Cv2.ImShow("minAreaRect", minAreaRectMat); Point2f center1 = rect1.Center; Mat rot_mat = Cv2.GetRotationMatrix2D(center1, (rect1.Angle % 90 == 0 ? 0 : rect1.Angle), 1.0); Mat rot_image = new Mat(); Cv2.WarpAffine(minAreaRectMat, rot_image, rot_mat, minAreaRectMat.Size()); Cv2.ImShow("rot_image", rot_image); var retMat = new Mat(rot_image, new Rect((int)Math.Round(center1.X - (rect1.Size.Width / 2), 0), (int)Math.Round(center1.Y - (rect1.Size.Height / 2), 0), (int)Math.Round(rect1.Size.Width, 0), (int)Math.Round(rect1.Size.Height, 0))); Cv2.ImShow("retMat", retMat); }
讯享网
测试原图:

测试结果:


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/106288.html