You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenCV裁剪图像矩形区域出现类型转换及语法错误如何解决?

报错原因与解决方案

报错根源

  • 第一个类型转换报错:OpenCV的Point类的x/y属性为double类型,而Rect构造函数的入参要求全部为int类型,直接传入double会触发精度丢失的编译校验错误。
  • 第二个语法报错:你的代码存在括号配对错误,且Rect构造函数参数格式不匹配:Rect仅支持Rect(int x, int y, int width, int height) 或者 Rect(Point p, Size s) 两种参数结构,你错误地给坐标和宽高套了多余的括号,导致编译器无法识别语法。

修正后的代码

String image = "myPhoto.jpg";
Mat myPhoto = Imgcodecs.imread(image);
Point p1 = new Point(300, 150);
Point p4 = new Point(400, 200);
// 强制转换double为int,修正括号与参数结构
Rect rectCrop = new Rect((int)p1.x, (int)p1.y, (int)(p4.x - p1.x + 1), (int)(p4.y - p1.y + 1));
Mat outputPhoto = myPhoto.submat(rectCrop);

如果偏好更易读的写法,也可以用Point+Size的构造方式:

// 第二种写法:通过Point+Size构造Rect
Rect rectCrop = new Rect(p1, new Size((int)(p4.x - p1.x + 1), (int)(p4.y - p1.y + 1)));

额外注意

调用前需要确认p4.x > p1.x、p4.y > p1.y,避免计算出负的宽高导致运行时异常。

内容的提问来源于stack exchange,提问作者Oliwier Piasecki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:15:03