您好,欢迎访问一九零五行业门户网

如何将OpenCV的Mat对象转换为JavaFX的WritableImage对象?

如果你尝试使用opencv的imread()方法读取图像,它会返回一个mat对象。如果你想使用javafx窗口显示结果mat对象的内容,你需要将mat对象转换为javafx.scene.image.writableimage类的对象。为了做到这一点,你需要按照以下步骤进行:
将mat编码为matofbyte - 首先,你需要将矩阵转换为字节矩阵。你可以使用imgcodecs类的imencode()方法来实现。
这个方法接受一个字符串参数(指定图像格式),一个mat对象(表示图像),一个matofbyte对象。
将matofbyte对象转换为字节数组 - 使用toarray()方法将matofbyte对象转换为字节数组。
实例化bytearrayinputstream - 通过将前一步骤中创建的字节数组传递给其构造函数之一,实例化bytearrayinputstream类。
创建bufferedimage对象 - 将前一步骤中创建的输入流对象传递给imageio类的read()方法。这将返回一个bufferedimage对象。
最后,通过将前一步骤中获得的bufferedimage对象作为参数,调用swingfxutils类的tofximage()方法。
示例import java.awt.image.bufferedimage;import java.io.bytearrayinputstream;import java.io.ioexception;import java.io.inputstream;import javax.imageio.imageio;import org.opencv.core.core;import org.opencv.core.mat;import org.opencv.core.matofbyte;import org.opencv.imgcodecs.imgcodecs;import javafx.embed.swing.swingfxutils;import javafx.scene.image.writableimage;public class mat2writableimage { public static writableimage mat2writableimage(mat mat) throws ioexception{ //encoding the image matofbyte matofbyte = new matofbyte(); imgcodecs.imencode(".jpg", mat, matofbyte); //storing the encoded mat in a byte array byte[] bytearray = matofbyte.toarray(); //preparing the buffered image inputstream in = new bytearrayinputstream(bytearray); bufferedimage bufimage = imageio.read(in); system.out.println("image loaded"); writableimage writableimage = swingfxutils.tofximage(bufimage, null); return writableimage; } public static void main(string args[]) throws exception { //loading the opencv core library system.loadlibrary( core.native_library_name ); //reading the image from the file string file = "c:/examples/opencv/sample.jpg"; mat image = imgcodecs.imread(file); writableimage obj = mat2writableimage(image); system.out.println(obj); }}
输出image loadedjavafx.scene.image.writableimage@142269f2
以上就是如何将opencv的mat对象转换为javafx的writableimage对象?的详细内容。
其它类似信息

推荐信息