Leptonica OpenCV Java convert Mat to Pix and vise versa

主宰稳场 提交于 2019-12-20 03:26:09

问题


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>

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.

This is what I have for now:

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 ?


回答1:


Try the following:

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);
}


来源:https://stackoverflow.com/questions/48868503/leptonica-opencv-java-convert-mat-to-pix-and-vise-versa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!