หากคุณพยายามอ่านรูปภาพโดยใช้ OpenCV imread() เมธอดจะส่งคืนวัตถุ Mat หากคุณต้องการแสดงเนื้อหาของวัตถุ Mat ที่เป็นผลลัพธ์โดยใช้หน้าต่าง JavaFX คุณต้องแปลงวัตถุ Mat เป็นวัตถุของคลาส javafx.scene.image.WritableImage คุณต้องทำตามขั้นตอนด้านล่าง -
-
เข้ารหัส Mat เป็น MatOfByte − ก่อนอื่น คุณต้องแปลงเมทริกซ์เป็นเมทริกซ์ขนาดไบต์ คุณสามารถทำได้โดยใช้วิธีการ imencode() ของคลาส Imgcodecs
-
เมธอดนี้ยอมรับพารามิเตอร์ String (ระบุรูปแบบรูปภาพ) วัตถุ Mat (แทนรูปภาพ) วัตถุ MatOfByte
-
แปลงวัตถุ MatOfByte เป็นอาร์เรย์ไบต์ − แปลงวัตถุ MatOfByte เป็นอาร์เรย์ไบต์โดยใช้เมธอด toArray()
-
อินสแตนซ์ ByteArrayInputStream − สร้างอินสแตนซ์ของคลาส ByteArrayInputStream โดยส่งอาร์เรย์ไบต์ที่สร้างในขั้นตอนก่อนหน้าไปยังหนึ่งในคอนสตรัคเตอร์
-
การสร้างวัตถุ BufferedImage − ส่งผ่านวัตถุ Input Stream ที่สร้างในขั้นตอนก่อนหน้าไปยังเมธอด read() ของคลาส ImageIO สิ่งนี้จะส่งคืนวัตถุ BufferedImage
-
สุดท้าย เรียกใช้ toFXImage() วิธีการของ SwingFXUtils คลาสโดยผ่าน BufferedImage วัตถุที่ได้รับในขั้นตอนก่อนหน้าเป็นพารามิเตอร์
ตัวอย่าง
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 Loaded javafx.scene.image.WritableImage@142269f2