Java Opencv开山之路–(1)–Java Opencv ROI图片裁剪

废话少说代码如下:

    /**
     * 按照指定的尺寸截取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();
    }

结果:
原始图
原始图

testCut

testCut2


看这里,看这里
文章总目录:博客导航
参考文章:https://blog.csdn.net/u_ascend/article/details/85006671

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值