Leptonica OpenCV Java将Mat转换为Pix,反之亦然 [英] Leptonica OpenCV Java convert Mat to Pix and vise versa

查看:138
本文介绍了Leptonica OpenCV Java将Mat转换为Pix,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下lept4jOpenCV Maven依赖项:

I use the following lept4j and OpenCV Maven dependencies:

<!-- Leptonica -->
<dependency>
    <groupId>net.sourceforge.lept4j</groupId>
    <artifactId>lept4j</artifactId>
    <version>1.9.0</version>
</dependency>

<!-- OpenCV -->
<dependency>
    <groupId>org.openpnp</groupId>
    <artifactId>opencv</artifactId>
    <version>3.2.0-1</version>
</dependency>

我想一起使用OpenCV和Leptonica函数.为此,我需要能够将Mat转换为Pix,并将Pix转换为Mat.

I'd like to use OpenCV and Leptonica functions together. In order to do this, I need to be able to convert Mat to Pix and Pix to Mat.

这是我现在拥有的:

public static Pix matToGrayscalePix(Mat mat) {

    if (mat == null) {
        throw new IllegalArgumentException("Recycled matrix");
    }

    final byte[] bytes = new byte[(int) mat.total()];
    mat.get(0, 0, bytes);

    ByteBuffer buff = ByteBuffer.wrap(bytes);
    return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity()));
}

public static Mat pixToGrayscaleMat(Pix pix) {

    if (pix == null) {
        throw new IllegalArgumentException("Recycled matrix");
    }

    PointerByReference pdata = new PointerByReference();
    NativeSizeByReference psize = new NativeSizeByReference();
    int format = net.sourceforge.lept4j.ILeptonica.IFF_TIFF;
    Leptonica1.pixWriteMem(pdata, psize, pix, format);
    byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue());

    return new MatOfByte(b).reshape(0, pix.h);
}

但是这些功能目前无法使用.我在做什么错了?

But these functions doesn't work right now. What am I doing wrong ?

推荐答案

尝试以下操作:

public static Pix convertMatToPix(Mat mat) {
    MatOfByte bytes = new MatOfByte();
    Imgcodecs.imencode(".tif", mat, bytes);
    ByteBuffer buff = ByteBuffer.wrap(bytes.toArray());
    return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity()));
}

public static Mat convertPixToMat(Pix pix) {
    PointerByReference pdata = new PointerByReference();
    NativeSizeByReference psize = new NativeSizeByReference();
    Leptonica1.pixWriteMem(pdata, psize, pix, ILeptonica.IFF_TIFF);
    byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue());
    Leptonica1.lept_free(pdata.getValue());
    return Imgcodecs.imdecode(new MatOfByte(b), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
}

这篇关于Leptonica OpenCV Java将Mat转换为Pix,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆