废话少说代码如下:
/**
* 按照指定的尺寸截取Mat,截取宽高自动计算(对称)。坐标原点为左上角
*
* @param src 源Mat
* @param x x
* @param y y
* @return 截取后的Mat
*/
public static Mat cut(Mat src, int x, int y) {
// 截取尺寸
int width = src.width() - 2 * x;
int height = src.height() - 2 * y;
return cut(src, x, y, width, height);
}
/**
* 按照指定的尺寸截取Mat,坐标原点为左上角
*
* @param src 源Mat
* @param x x
* @param y y
* @param width width
* @param height height
* @return 截取后的Mat
*/
public static Mat cut(Mat src, int x, int y, int width, int height) {
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (width > src.width()) {
width = src.width();
}
if (height > src.height()) {
height = src.height();
}
// 截取尺寸
Rect rect = new Rect(x, y, width, height);
return new Mat(src, rect);
}
测试代码:
@Test
public void testCut() {
Mat dog = Imgcodecs.imread("/tmp/dog.jpg");
Mat smallDog = ImageUtils.cut(dog, 0, 0, 5000, 5000);
showImg(smallDog);
}
@Test
public void testCut2() {
Mat dog = Imgcodecs.imread("/tmp/dog.jpg");
Mat smallDog = ImageUtils.cut(dog, 200, 200);
showImg(smallDog);
}
private void showImg(Mat mat) {
HighGui.imshow("结果", mat);
HighGui.waitKey();
}
结果:
原始图
看这里,看这里
文章总目录:博客导航
参考文章:https://blog.csdn.net/u_ascend/article/details/85006671