基于Java+OpnenCV的图像读取与显示

来源:互联网 发布:中国骨科手术量数据 编辑:程序博客网 时间:2024/06/17 15:03

本程序实现基于Java和Opencv的图像读取与显示。

开发环境:Eclipse4.6,JDK1.8+Opencv3.0

注:学习心得,仅供参考。如有错误,请不吝指教。

【直接贴源代码】

package opencvTest;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 {/*调用opencv的库之前,得要有下面的代码来加载*/static{System.loadLibrary(Core.NATIVE_LIBRARY_NAME);}private JFrame frame;/* * Launch the application. */public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {ShowImage window = new ShowImage();window.frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/* * Create the application. */public ShowImage() {initialize();}/* * Initialize the contents of the frame. */private void initialize() {frame = new JFrame();frame.setBounds(100, 100, 800, 450);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.getContentPane().setLayout(null);JLabel label = new JLabel("");label.setBounds(0, 0, 800, 450);frame.getContentPane().add(label);Mat source=Imgcodecs.imread("sky.jpg");//加载sky图像为Mat格式//注:图像应位于当前工程路径下//BufferedImage image=mat2BufferedImage.matToBufferedImage(source);label.setIcon(new ImageIcon(image));}}//将Opencv中Mat格式的图像转换成Java Swing中的BufferedImage格式//因为在Swing中只支持BufferedImage格式图像显示。class mat2BufferedImage {public static BufferedImage matToBufferedImage(Mat matrix) {int cols = matrix.cols();int rows = matrix.rows();int elemSize = (int) matrix.elemSize();byte[] data = new byte[cols * rows * elemSize];int type;matrix.get(0, 0, data);switch (matrix.channels()) {case 1:type = BufferedImage.TYPE_BYTE_GRAY;break;case 3:type = BufferedImage.TYPE_3BYTE_BGR;// bgr to rgbbyte b;for (int i = 0; i < data.length; i = i + 3) {b = data[i];data[i] = data[i + 2];data[i + 2] = b;}break;default:return null;}BufferedImage image2 = new BufferedImage(cols, rows, type);image2.getRaster().setDataElements(0, 0, cols, rows, data);return image2;}}

实现效果:




0 0