app.GUI2.java Source code

Java tutorial

Introduction

Here is the source code for app.GUI2.java

Source

/*
 * 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.
 */
package app;

import java.awt.Image;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.opencv.core.Mat;
import app.utils.ImageProcessor;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.sourceforge.tess4j.TesseractException;
import org.opencv.core.Core;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

/**
 *
 * @author Zygis
 */
public class GUI2 extends javax.swing.JFrame {

    /**
     * Creates new form GUI2
     */
    public GUI2() {
        initComponents();
    }

    static {
        // this will check architecture and dinamikli load
        //        System.out.println(System.getProperty("user.dir"));
        String workingPath = System.getProperty("user.dir");
        String arch = System.getProperty("sun.arch.data.model");
        String sep = File.separator;
        //        System.setProperty( "java.library.path", "libs" );
        if (arch.equals("64")) {
            String path = workingPath + sep + "libs" + sep + "x64" + sep + "opencv_java310.dll";
            //            System.setProperty( "java.library.path", "libs" );
            System.load(path);
        } else if (arch.equals("32")) {
            String path = workingPath + sep + "libs" + sep + "x86" + sep + "opencv_java310.dll";
            System.load(path);
            //            System.loadLibrary("opencv_java310");
        } else {
            System.out.println("different architecture?: " + arch);
        }

        //        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        imageView = new javax.swing.JPanel();
        imageViewL = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jRadioButtonA1 = new javax.swing.JRadioButton();
        jRadioButtonA2 = new javax.swing.JRadioButton();
        jTextFieldA1 = new javax.swing.JTextField();
        jTextFieldA2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jRadioButtonB1 = new javax.swing.JRadioButton();
        jTextFieldB1 = new javax.swing.JTextField();
        jRadioButtonB2 = new javax.swing.JRadioButton();
        jTextFieldB2 = new javax.swing.JTextField();

        jScrollPane2.setViewportView(jEditorPane1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        imageViewL.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                imageViewLMousePressed(evt);
            }
        });

        javax.swing.GroupLayout imageViewLayout = new javax.swing.GroupLayout(imageView);
        imageView.setLayout(imageViewLayout);
        imageViewLayout.setHorizontalGroup(imageViewLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(imageViewLayout.createSequentialGroup().addContainerGap()
                        .addComponent(imageViewL, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
                        .addContainerGap()));
        imageViewLayout
                .setVerticalGroup(imageViewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                imageViewLayout
                                        .createSequentialGroup().addContainerGap().addComponent(imageViewL,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
                                        .addContainerGap()));

        jScrollPane1.setViewportView(imageView);

        jButton1.setText("Select image");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Start");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Renctagle for matrix");

        buttonGroup1.add(jRadioButtonA1);
        jRadioButtonA1.setText("PointA1");
        jRadioButtonA1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonA1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButtonA2);
        jRadioButtonA2.setText("PointA2");
        jRadioButtonA2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonA2ActionPerformed(evt);
            }
        });

        jTextFieldA1.setEditable(false);
        jTextFieldA1.setText("X: - ; Y : - ;");
        jTextFieldA1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldA1ActionPerformed(evt);
            }
        });

        jTextFieldA2.setEditable(false);
        jTextFieldA2.setText("X: - ; Y : - ;");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Renctagle for word list");

        buttonGroup1.add(jRadioButtonB1);
        jRadioButtonB1.setText("PointB1");
        jRadioButtonB1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonB1ActionPerformed(evt);
            }
        });

        jTextFieldB1.setEditable(false);
        jTextFieldB1.setText("X: - ; Y : - ;");

        buttonGroup1.add(jRadioButtonB2);
        jRadioButtonB2.setText("PointB2");
        jRadioButtonB2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonB2ActionPerformed(evt);
            }
        });

        jTextFieldB2.setEditable(false);
        jTextFieldB2.setText("X: - ; Y : - ;");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(jPanel2Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addGroup(
                        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel1)
                                .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jRadioButtonA2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextFieldA2))
                                .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jRadioButtonA1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextFieldA1, javax.swing.GroupLayout.PREFERRED_SIZE, 120,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(16, 16, 16)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2)
                                .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jRadioButtonB2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextFieldB2, javax.swing.GroupLayout.DEFAULT_SIZE, 120,
                                                Short.MAX_VALUE))
                                .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jRadioButtonB1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextFieldB1)))
                        .addContainerGap(61, Short.MAX_VALUE)));
        jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jRadioButtonB1).addComponent(jTextFieldB1,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jRadioButtonB2).addComponent(jTextFieldB2,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8,
                                                Short.MAX_VALUE)
                                        .addGroup(jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jButton1).addComponent(jRadioButtonA1)
                                                .addComponent(jTextFieldA1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jButton2).addComponent(jRadioButtonA2)
                                                .addComponent(jTextFieldA2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(24, 24, 24)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0,
                                        Short.MAX_VALUE)
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(4, 4, 4)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jRadioButtonA1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonA1ActionPerformed
        pointA1 = new Point();
        pointerToPoint = pointA1;
        pointerToJextField = jTextFieldA1;
    }//GEN-LAST:event_jRadioButtonA1ActionPerformed

    private void jRadioButtonA2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonA2ActionPerformed
        pointA2 = new Point();
        pointerToPoint = pointA2;
        pointerToJextField = jTextFieldA2;
    }//GEN-LAST:event_jRadioButtonA2ActionPerformed

    private void jRadioButtonB1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonB1ActionPerformed
        pointB1 = new Point();
        pointerToPoint = pointB1;
        pointerToJextField = jTextFieldB1;
    }//GEN-LAST:event_jRadioButtonB1ActionPerformed

    private void jRadioButtonB2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonB2ActionPerformed
        pointB2 = new Point();
        pointerToPoint = pointB2;
        pointerToJextField = jTextFieldB2;
    }//GEN-LAST:event_jRadioButtonB2ActionPerformed

    /**
     * loads path to image, load picture to view
     *
     * @param evt
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Reset();
        final JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir") + "\\resource"));
        FileNameExtensionFilter filter = new FileNameExtensionFilter("IMAGE FILES", "jpg", "jpg");
        fc.setFileFilter(filter);
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            imagePath = fc.getSelectedFile().toString();
            //            System.out.println("File path: " + imagePath + ".");
        } else {
            //            System.out.println(System.getProperty("user.dir") + "\\resource");
        }

        originalImage = Imgcodecs.imread(imagePath);
        updateView(originalImage);
        //        System.out.println(returnVal);
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * get coordinates from image when pressed on it
     *
     * @param evt
     */
    private void imageViewLMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imageViewLMousePressed

        if (pointerToJextField != null & pointerToPoint != null) {
            //            pointerToJextField.setText("X: "+ +";Y: ");
            pointerToPoint.x = evt.getX();
            pointerToPoint.y = evt.getY();
            pointerToJextField.setText("X: " + pointerToPoint.x + ";Y: " + pointerToPoint.y + ";");
            //          System.out.println(buttonGroup1.getSelection() + "| " + evt.getX() + " " + evt.getY());
            //            System.out.println(pointerToPoint);
            //            System.out.print(pointA1);
            //            System.out.print(pointA2);
            //            System.out.print(pointB1);
            //            System.out.println(pointB2);

        }

        updateDrawings(this.originalImage);
    }//GEN-LAST:event_imageViewLMousePressed

    private void jTextFieldA1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldA1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldA1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            image = AppMain.procesImage(originalImage.clone(), pointA1, pointA2, pointB1, pointB2);
            updateDrawings(image);
        } catch (TesseractException ex) {
            Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * this function preproces image to draw helper figures on top of image and
     * then calls updateView()
     */
    private void updateDrawings(Mat unprocesedImage) {
        try {
            image = unprocesedImage.clone();
            // draw Points as circles
            if (pointA1 != null) {
                Imgproc.circle(image, pointA1, 10, new Scalar(0, 0, 128), 2);
            }
            if (pointA2 != null) {
                Imgproc.circle(image, pointA2, 10, new Scalar(0, 0, 255), 2);
            }
            if (pointB1 != null) {
                Imgproc.circle(image, pointB1, 10, new Scalar(128, 0, 0), 2);
            }
            if (pointB2 != null) {
                Imgproc.circle(image, pointB2, 10, new Scalar(255, 0, 0), 2);
            }
            // draw rectangles of selected circles
            if (pointA1 != null & pointA2 != null) {
                Imgproc.rectangle(image, pointA1, pointA2, new Scalar(0, 0, 255), 2);
            }
            if (pointB1 != null & pointB2 != null) {
                Imgproc.rectangle(image, pointB1, pointB2, new Scalar(255, 0, 0), 2);
            }

            updateView(image);
        } catch (Exception e) {
            System.err.println("Tryied to Draw without loading image" + e);
        }

    }

    private void updateView(Mat newMat) {

        Image outputImage = imageProcessor.toBufferedImage(newMat);
        imageViewL.setIcon(new ImageIcon(outputImage));

    }

    /**
     * reset all variables to default
     */
    private void Reset() {
        this.imagePath = null;
        this.image = null;
        this.originalImage = null;
        this.pointA1 = null;
        this.pointA2 = null;
        this.pointB1 = null;
        this.pointB2 = null; // points of subimages

        // this are pointers are used with radio buttons
        this.pointerToPoint = null;
        this.pointerToJextField = null;

        jTextFieldA1.setText(coordinatePlaceholder);
        jTextFieldA2.setText(coordinatePlaceholder);
        jTextFieldB1.setText(coordinatePlaceholder);
        jTextFieldB2.setText(coordinatePlaceholder);

        buttonGroup1.clearSelection();
    }

    /**
     * @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(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI2.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() {
                new GUI2().setVisible(true);
            }
        });
    }

    // user difined variables
    private String imagePath;
    private Mat image, originalImage;

    // points of subimages
    private Point pointA1 = null;
    private Point pointA2 = null;
    private Point pointB1 = null;
    private Point pointB2 = null;

    // this are pointers are used with radio buttons
    private Point pointerToPoint;
    private JTextField pointerToJextField;

    private final String coordinatePlaceholder = "X: - ; Y : - ;";
    private final ImageProcessor imageProcessor = new ImageProcessor();

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JPanel imageView;
    private javax.swing.JLabel imageViewL;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton jRadioButtonA1;
    private javax.swing.JRadioButton jRadioButtonA2;
    private javax.swing.JRadioButton jRadioButtonB1;
    private javax.swing.JRadioButton jRadioButtonB2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextFieldA1;
    private javax.swing.JTextField jTextFieldA2;
    private javax.swing.JTextField jTextFieldB1;
    private javax.swing.JTextField jTextFieldB2;
    // End of variables declaration//GEN-END:variables

}

//// snipets
//        ButtonModel selectedJRadioButton = buttonGroup1.getSelection();
//        if (selectedJRadioButton == jRadioButtonA1) {
//            System.out.println("worksA1");
//        } else if (selectedJRadioButton == jRadioButtonA2) {
//            System.out.println("worksA2");
//        } else if (selectedJRadioButton == jRadioButtonB1) {
//            System.out.println("worksB1");
//        } else if (selectedJRadioButton == jRadioButtonB2) {
//            System.out.println("worksB2");
//        } else {
//            System.out.println("Shit happenened");
//        }