1

How to convert mat(OpenCV) to image(JavaFX)? I think this isn't not best method:

MatOfByte byteMat = new MatOfByte();
Highgui.imencode(".bmp", mat, byteMat);
return new Image(new ByteArrayInputStream(byteMat.toArray()));

P.S.

Image - import javafx.scene.image.Image;

2 Answers 2

0

One way to do it would be this.I do not remember the source from where I got this:-

private Image mat2Image(Mat frame)
{
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if ( frame.channels() > 1 ) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    int bufferSize = frame.channels()*frame.cols()*frame.rows();
    byte [] b = new byte[bufferSize];
    frame.get(0,0,b); // get all the pixels
    BufferedImage image = new BufferedImage(frame.cols(),frame.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return SwingFXUtils.toFXImage(image,null);

}

There may be a way to make it neater using the Converters class from Opencv along with JDK8. I will update this if I find any such thing.

Sign up to request clarification or add additional context in comments.

Comments

0

Paritosh, the issue with your method is that it only applies to the Mats with the type of CvType.CV_8U or CvType.CV_8S, since those Mats can be contained in a byte array. If the type of the Mat is, lets say, CvType.CV_32F, you would need a float array to hold the data. The float array cannot be System.arraycopied into a byte[] targetPixels array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.