Belajar OpenCV di Java Bagian 2

By | July 30, 2024
1,475 Views

Kita akan lanjutkan pembahasan OpenCV di Java dibagian sebelumnya yaitu menggunakan JFrame untuk menampilkan gambar serta diberikan feature untuk resize gambar. Editor yang kita gunakan berupa Netbeans agar mudah dalam drag and drop component SWING/AWT. Pembuatan aplikasi OpenCV di java  sangat mudah koq, apalagi kalau menggunakan Netbeans.

Tampilan Aplikasi

Tampilan aplikasi OpenCV di Java untuk menampilkan gambar seperti berikut

Terdapat File Menu Buka untuk membuat gambar, serta slider untuk menentukan ratio resizenya, adapun component utamanya yaitu JScrollPane dan JLabel sebagai wadah untuk menampilkan gambar

Import Libary yang dibutuhkan

Oiya jangan lupa ya, kalian setting library OpenCV nya, baca sebelumnya. Berikut daftar import libary yang dibutuhkan

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;

Variabel Global dan tambahan Kode pada method Constructor

Kita akan nambahkan variable global yaitu

Mat current ;

terus tambahkan kode berikut didalam method constructor untuk memastikan bahwa library OpenCV akan diload

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

 

Buat method untuk mengubah Mat ke BufferedImage

Untuk mempermudah pengubahan object class Mat ke BufferedImage, kita buatkan private methode yaitu

private BufferedImage Mat2BufferedImage(Mat matrix)throws Exception {        
    MatOfByte mob=new MatOfByte();
    Imgcodecs.imencode(".jpg", matrix, mob);
    byte ba[]=mob.toArray();

    BufferedImage bi=ImageIO.read(new ByteArrayInputStream(ba));
    return bi;
}

 

Action Performed ketika Buka dipilih user

Tambahkan kode berikut ketika user memilih menu Buka

JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    System.out.println("Selected file: " + selectedFile.getAbsolutePath());
    Imgcodecs imageCodecs = new Imgcodecs();
    Mat matrix = Imgcodecs.imread(selectedFile.getAbsolutePath(),Imgcodecs.IMREAD_REDUCED_COLOR_2);
    current = matrix.clone();
    try {
        this.jLabel1.setIcon(new ImageIcon(Mat2BufferedImage(matrix)));
    } catch (Exception ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

}

Action StateChanged ketika Slider digerakan

Berikut kode yang digunakan ketika slider sedang digeser

if (current==null) return;

double ratio = this.jSlider1.getValue();
ratio /= 100;
if (ratio==00) return;

setTitle("Ukuran: "+ratio);
int endl=0;
Mat buff = new Mat();

Size scaleSize = new Size((int)(this.current.cols()*ratio),
                        (int)(this.current.rows()*ratio));

Imgproc.resize(this.current,buff, scaleSize , 0, 0, Imgproc.INTER_AREA);
BufferedImage buf;
try {
    buf = Mat2BufferedImage(buff);
    this.jLabel1.setIcon(new ImageIcon(buf));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
} catch (Exception ex) {
    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}

 

See also  Belajar OpenCV bagian 1 - Setting OpenCV di Java

Kode lengkapnya bisa kalian pelajari di NewJFrame.java berikut ini

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;    

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author bejo
 */
public class NewJFrame extends javax.swing.JFrame {
    Mat current ;

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() throws IOException, Exception {
        initComponents();
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jLabel1 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jScrollPane1.setViewportView(jLabel1);

        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        jMenu1.setText("File");

        jMenuItem1.setText("Buka");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 539, Short.MAX_VALUE)
                    .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    
    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {                                      
        // TODO add your handling code here:
        if (current==null) return;
        
        double ratio = this.jSlider1.getValue();
        ratio /= 100;
        if (ratio==00) return;
        
        setTitle("Ukuran: "+ratio);
        int endl=0;
        Mat buff = new Mat();
        
        Size scaleSize = new Size((int)(this.current.cols()*ratio),
                                (int)(this.current.rows()*ratio));
        
        Imgproc.resize(this.current,buff, scaleSize , 0, 0, Imgproc.INTER_AREA);
        BufferedImage buf;
        try {
            buf = Mat2BufferedImage(buff);
            this.jLabel1.setIcon(new ImageIcon(buf));
            jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        } catch (Exception ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }                                     

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            System.out.println("Selected file: " + selectedFile.getAbsolutePath());
            Imgcodecs imageCodecs = new Imgcodecs();
            Mat matrix = Imgcodecs.imread(selectedFile.getAbsolutePath(),Imgcodecs.IMREAD_REDUCED_COLOR_2);
            current = matrix.clone();
            try {
                this.jLabel1.setIcon(new ImageIcon(Mat2BufferedImage(matrix)));
            } catch (Exception ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        
        }
        
    }                                          

    private BufferedImage Mat2BufferedImage(Mat matrix)throws Exception {        
        MatOfByte mob=new MatOfByte();
        Imgcodecs.imencode(".jpg", matrix, mob);
        byte ba[]=mob.toArray();

        BufferedImage bi=ImageIO.read(new ByteArrayInputStream(ba));
        return bi;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new NewJFrame().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSlider jSlider1;
    // End of variables declaration                   
}

Kinerja Aplikasi

Untuk kinerja aplikasi tidak ada lag karena operasi resize secara langsung menggunakan OpenCV berupa object class Mat.

See also  Membuat Scanner Document Corner Detection OpenCV Java