Java(opencv) 窗体打开摄像头

整个程序下载地址:Java(opencv) 窗体打开摄像头,并做一个灰度话处理,以后有关图像处理的和opencv的没有太大的区别

在testVideo项目下创建VideoIO包,包下新建ShowVideo.java窗体应用。

Java(opencv) 窗体打开摄像头_第1张图片


直接来看ShowVideo.java程序内容部分:

package VedioIO;

import java.awt.EventQueue;

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

import javax.swing.JButton;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.videoio.VideoCapture;
import org.opencv.imgproc.Imgproc;
import tool.mat2BufferedImage;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ShowVedio {

	static{System.loadLibrary(Core.NATIVE_LIBRARY_NAME);}
	private JFrame frame;
	static JLabel label;
	static int flag=0;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ShowVedio window = new ShowVedio();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		//操作
		VideoCapture camera=new VideoCapture();
		camera.open(1);
		if(!camera.isOpened()){
			System.out.println("Camera Error");
		}
		else{
			Mat frame=new Mat();
			while(flag==0){
				camera.read(frame);
				Mat gray=new Mat(frame.rows(),frame.cols(),frame.type());
				Imgproc.cvtColor(frame, gray, Imgproc.COLOR_RGB2GRAY);
				label.setIcon(new ImageIcon(mat2BufferedImage.matToBufferedImage(gray)));
				try{
					Thread.sleep(100);
				}
				catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Create the application.
	 */
	public ShowVedio() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 798, 600);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
				
		JButton btnNewButton = new JButton("拍照");
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				flag=1;
			}
		});
		btnNewButton.setBounds(20, 20, 113, 27);
		frame.getContentPane().add(btnNewButton);
		
		label=new JLabel("");
		label.setBounds(50, 50, 640, 480);
		frame.getContentPane().add(label);
	}

}

关于
import tool.mat2BufferedImage;
在上一篇文章中已经贴出来了,这里就不写了。
Java(opencv)窗体中显示图像。 mat2BufferedImage可以查看这篇文章

结果显示:
Java(opencv) 窗体打开摄像头_第2张图片


你可能感兴趣的:(Java)