package com.mengchicmc;
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by MengchiCMC on 2017-6-14.
*/
public class MatView {
/**
* Open a image file
*
* @param filePath the path of the image to open
* @return image in the form of Mat
* @throws Exception There is no image to open in this file path
*/
public static Mat openFile(String filePath) throws Exception {
Mat image = new Mat();
image = Imgcodecs.imread(filePath);
if (image.dataAddr() == 0) {
throw new Exception("Couldn't open file");
}
return image;
}
/**
* Display Mat image
*
* @param image
*/
public static void imshow(Mat image) {
imshow(image, image.cols(), image.rows(), "");
}
public static void imshow(Mat image, String windowName) {
imshow(image, image.cols(), image.rows(), windowName);
}
public static void imshow(Mat image, int width, int height) {
imshow(image, width, height, "");
}
public static void imshow(Mat image, int width, int height, String windowName) {
if (image.dataAddr() != 0) {
setSystemLookAndFeel();
JFrame jFrame = new JFrame(windowName);
JLabel imageView = new JLabel();
final JScrollPane imageScrollPane = new JScrollPane(imageView);
imageScrollPane.setPreferredSize(new Dimension(width, height)); // set window size
jFrame.add(imageScrollPane, BorderLayout.CENTER);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Image loadedImage = Mat2BufferedImage(image);
imageView.setIcon(new ImageIcon(loadedImage));
jFrame.pack();
jFrame.setLocationRelativeTo(null);
jFrame.setVisible(true);
} else {
System.out.println("Mat is empty!");
}
}
private static void setSystemLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
/**
* Transform picture type from Mat to BufferedImage
*
* @param matrix
* @return
*/
public static Image Mat2BufferedImage(Mat matrix) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if (matrix.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR; // **B G R**
}
int bufferSize = matrix.channels() * matrix.cols() * matrix.rows();
byte[] buffer = new byte[bufferSize];
matrix.get(0, 0, buffer); // get all the pixels
BufferedImage image = new BufferedImage(matrix.cols(), matrix.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
return image;
}
}