หากคุณอ่านภาพด้วย OpenCV imread() จะคืนค่า Mat object หากต้องการแสดงเนื้อหาของ Mat object ผ่านหน้าต่าง AWT/Swing คุณต้องแปลง Mat object เป็นอ็อบเจ็กต์ของคลาส java.awt.image.BufferedImage ขั้นตอนมีดังนี้:
- Encode Mat เป็น MatOfByte - ก่อนอื่น แปลง matrix เป็น matrix ของ byte ด้วยเมธอด imencode() ของคลาส Imgcodecs
เมธอดนี้รับพารามิเตอร์: String (รูปแบบภาพ), Mat object (ภาพ), MatOfByte object - แปลง MatOfByte เป็น byte array - แปลง MatOfByte object เป็น byte array ด้วยเมธอด toArray()
- สร้าง ByteArrayInputStream - สร้างอินสแตนซ์ ByteArrayInputStream โดยส่ง byte array ที่ได้
- สร้าง BufferedImage object - ส่ง Input Stream object ให้เมธอด read() ของคลาส ImageIO จะคืนค่า BufferedImage object
ตัวอย่างโค้ด
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;
public class Mat2BufferedImage {
public static BufferedImage Mat2BufferedImage(Mat mat) throws IOException {
// Encode ภาพ
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", mat, matOfByte);
// เก็บ encoded Mat ใน byte array
byte[] byteArray = matOfByte.toArray();
// เตรียม Buffered Image
InputStream in = new ByteArrayInputStream(byteArray);
BufferedImage bufImage = ImageIO.read(in);
return bufImage;
}
public static void main(String[] args) throws Exception {
// โหลด OpenCV core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// อ่านภาพจากไฟล์
String file = "C:/EXAMPLES/OpenCV/sample.jpg";
Mat image = Imgcodecs.imread(file);
BufferedImage obj = Mat2BufferedImage(image);
System.out.println(obj);
}
}
ผลลัพธ์
BufferedImage@579bb367: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1de0aca6 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 500 height = 360 #numDataElements 3 dataOff[0] = 2