OpenCV - GUI
En los capítulos anteriores, hemos discutido cómo leer y guardar una imagen usando la biblioteca OpenCV Java. Además, también podemos mostrar las imágenes cargadas en una ventana separada usando bibliotecas GUI como AWT / Swings y JavaFX.
Conversión de tapete en imagen con búfer
Para leer una imagen usamos el método imread(). Este método devuelve la imagen leída en forma deMatrix. Pero, para usar esta imagen con bibliotecas GUI (AWT / Swings y JavaFX), debe convertirse como un objeto de la claseBufferedImage del paquete java.awt.image.BufferedImage.
Los siguientes son los pasos para convertir un Mat objeto de OpenCV para BufferedImage objeto.
Paso 1: codifique el Mat en MatOfByte
En primer lugar, debe convertir la matriz en una matriz de bytes. Puedes hacerlo usando el métodoimencode() de la clase Imgcodecs. A continuación se muestra la sintaxis de este método.
imencode(ext, image, matOfByte);
Este método acepta los siguientes parámetros:
Ext - Un parámetro de cadena que especifica el formato de la imagen (.jpg, .png, etc.)
image - Un objeto Mat de la imagen
matOfByte - Un objeto vacío de la clase MatOfByte
Codifique la imagen utilizando este método como se muestra a continuación.
//Reading the image
Mat image = Imgcodecs.imread(file);
//instantiating an empty MatOfByte class
MatOfByte matOfByte = new MatOfByte();
//Converting the Mat object to MatOfByte
Imgcodecs.imencode(".jpg", image, matOfByte);
Paso 2: Convierta el objeto MatOfByte en una matriz de bytes
Convertir el MatOfByte objeto en una matriz de bytes usando el método toArray().
byte[] byteArray = matOfByte.toArray();
Paso 3: preparar el objeto InputStream
Prepare el objeto InputStream pasando la matriz de bytes creada en el paso anterior al constructor del ByteArrayInputStream clase.
//Preparing the InputStream object
InputStream in = new ByteArrayInputStream(byteArray);
Paso 4: preparación del objeto InputStream
Pase el objeto Flujo de entrada creado en el paso anterior al read() método del ImageIOclase. Esto devolverá un objeto BufferedImage.
//Preparing the BufferedImage
BufferedImage bufImage = ImageIO.read(in);
Visualización de imágenes usando AWT / Swings
Para mostrar una imagen usando el marco AWT / Swings, en primer lugar, lea una imagen usando el imread() método y convertirlo en BufferedImage siguiendo los pasos antes mencionados.
Luego, instancia el JFrame class y agregue la imagen almacenada en búfer creada al ContentPane del JFrame, como se muestra a continuación:
//Instantiate JFrame
JFrame frame = new JFrame();
//Set Content to the JFrame
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);
Example
El siguiente código de programa muestra cómo puede read una imagen y display a través de la ventana oscilante utilizando la biblioteca OpenCV.
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
public class DisplayingImagesUsingSwings {
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 and storing it in to a Matrix object
String file = "C:/EXAMPLES/OpenCV/sample.jpg";
Mat image = Imgcodecs.imread(file);
//Encoding the image
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", image, 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);
//Instantiate JFrame
JFrame frame = new JFrame();
//Set Content to the JFrame
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);
System.out.println("Image Loaded");
}
}
Al ejecutar el programa anterior, obtendrá el siguiente resultado:
Image Loaded
Además de eso, puede ver una ventana que muestra la imagen cargada, de la siguiente manera:
Visualización de imágenes usando JavaFX
Para mostrar una imagen usando JavaFX, en primer lugar, lea una imagen usando el imread() método y convertirlo en BufferedImage. Luego, convierta BufferedImage en WritableImage, como se muestra a continuación.
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
Pasa esto WritableImage objeto al constructor del ImageView clase.
ImageView imageView = new ImageView(writableImage);
Example
El siguiente código de programa muestra cómo read una imagen y display a través de la ventana JavaFX utilizando la biblioteca OpenCV.
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
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 DisplayingImagesJavaFX extends Application {
@Override
public void start(Stage stage) throws IOException {
WritableImage writableImage = loadImage();
//Setting the image view
ImageView imageView = new ImageView(writableImage);
//Setting the position of the image
imageView.setX(50);
imageView.setY(25);
//setting the fit height and width of the image view
imageView.setFitHeight(400);
imageView.setFitWidth(500);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 400);
//Setting title to the Stage
stage.setTitle("Loading an image");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public WritableImage loadImage() throws IOException {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image from the file and storing it in to a Matrix object
String file ="C:/EXAMPLES/OpenCV/sample.jpg";
Mat image = Imgcodecs.imread(file);
//Encoding the image
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", image, matOfByte);
//Storing the encoded Mat in a byte array
byte[] byteArray = matOfByte.toArray();
//Displaying the 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[]) {
launch(args);
}
}
Al ejecutar el programa anterior, obtendrá el siguiente resultado:
Image Loaded
Además de eso, puede ver una ventana que muestra la imagen cargada, de la siguiente manera: