Java Opencv读取图片并显示
程序员文章站
2022-03-19 22:13:32
...
本篇博客介绍如何在Java中使用Opencv实现对图片的读取和显示。
首先是显示部分:
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
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.imgcodecs.Imgcodecs;
public class ShowImage {
private JFrame frame;
/**
* Create the application.
*/
public ShowImage(Mat mat) {
initialize(mat);
}
public JFrame getFrame() {
return frame;
}
/**
* Initialize the contents of the frame.
*/
private void initialize(Mat mat) {
frame = new JFrame();
frame.setBounds(20, 100, mat.width()+100, mat.height()+80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
BufferedImage image=new MatToBufImg(mat, ".png").getImage();
JLabel label = new JLabel(""){
@Override
public void setLabelFor(Component c) {
// TODO Auto-generated method stub
super.setLabelFor(c);
}
};
label.setBounds(0, 0, mat.width(), mat.height());
frame.getContentPane().add(label);
label.setIcon(new ImageIcon(image));
}
}
将Mat类型的图片转化为BufferedImage类型:import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
public class MatToBufImg {
Mat matrix;
MatOfByte mob;
String fileExten;
// The file extension string should be ".jpg", ".png", etc
public MatToBufImg(Mat amatrix, String fileExtension) {
matrix = amatrix;
fileExten = fileExtension;
mob = new MatOfByte();
}
public BufferedImage getImage() {
// convert the matrix into a matrix of bytes appropriate for
// this file extension
Imgcodecs.imencode(fileExten, matrix, mob);
// convert the "matrix of bytes" into a byte array
byte[] byteArray = mob.toArray();
BufferedImage bufImage = null;
try {
InputStream in = new ByteArrayInputStream(byteArray);
bufImage = ImageIO.read(in);
} catch (Exception e) {
e.printStackTrace();
}
return bufImage;
}
}
主类:
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public class Main{
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String originalImgPath = "img/1.png";
Mat mat = Imgcodecs.imread(originalImgPath);
ShowImage window = new ShowImage(mat);
window.getFrame().setVisible(true);
}
}
上一篇: 记一次灰产创业史