opencvjava显示mat对象的方法

opencvjava显示mat对象的方法


直接ctrl+c,ctrl+v创建对象调用imgshow方法即可

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

import org.opencv.core.Mat;

public class ShowImages{
	Mat mat;
	JLabel imageView;
	public ShowImages(Mat mat){
		//接收图片
		this.mat=mat;
	}
	public void imshow() { 
		  
		 Image loadedImage = toBufferedImage(mat);
		 JFrame frame = createJFrame(mat.width(), mat.height()); 
		 imageView.setIcon(new ImageIcon(loadedImage)); 
		 frame.pack(); 
		 frame.setLocationRelativeTo(null);
		 frame.setVisible(true); 
		
		 
	 }
	private JFrame createJFrame( int width, int height) { 
		JFrame frame = new JFrame();
		imageView = new JLabel();
		final JScrollPane imageScrollPane = new JScrollPane(imageView);
		imageScrollPane.setPreferredSize(new Dimension(width, height)); 
		frame.add(imageScrollPane, BorderLayout.CENTER); 
		return frame; 
		}
	
	private Image toBufferedImage(Mat matrix) { 
		int type = BufferedImage.TYPE_BYTE_GRAY;
		if (matrix.channels() > 1) { 
			type = BufferedImage.TYPE_3BYTE_BGR;
			} 
		int bufferSize = matrix.channels() * matrix.cols() * matrix.rows(); 
		byte[] buffer = new byte[bufferSize];
		matrix.get(0, 0, buffer); 
		// 获取所有的像素点
		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; 
		}
	 
	 
	

}

你可能感兴趣的:(图像识别)