1. 程式人生 > >【Java Opencv系列】4.3讀取攝像頭並顯示

【Java Opencv系列】4.3讀取攝像頭並顯示

程式碼如下:

package imageIO;

import java.awt.EventQueue;

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.videoio.VideoCapture;

import tool.mat2BufferedImage;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CameraBasic {
	
	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 {
					CameraBasic window = new CameraBasic();
					window.frame.setVisible(true);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		//我們的操作
		VideoCapture camera=new VideoCapture();//建立Opencv中的視訊捕捉物件
		camera.open(0);//open函式中的0代表當前計算機中索引為0的攝像頭,如果你的計算機有多個攝像頭,那麼一次1,2,3……
		if(!camera.isOpened()){//isOpened函式用來判斷攝像頭呼叫是否成功
			System.out.println("Camera Error");//如果攝像頭呼叫失敗,輸出錯誤資訊
		}
		else{
			Mat frame=new Mat();//建立一個輸出幀
			while(flag==0){
				camera.read(frame);//read方法讀取攝像頭的當前幀
				label.setIcon(new ImageIcon(mat2BufferedImage.matToBufferedImage(frame)));//轉換影象格式並輸出
				try {
					Thread.sleep(100);//執行緒暫停100ms
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Create the application.
	 */
	public CameraBasic() {
		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);
		
		JButton btnNewButton = new JButton("\u62CD\u7167");
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				flag=1;//靜態變數設定為1,從而按下按鈕時會停止攝像頭的呼叫
			}
		});
		btnNewButton.setBounds(33, 13, 113, 27);
		frame.getContentPane().add(btnNewButton);
		
		label = new JLabel("");
		label.setBounds(0, 0, 800, 450);
		frame.getContentPane().add(label);	
	}
}

最為重要的:VideoCapture類以及read方法。在程式碼的註釋中已經說明了使用的方法。

執行結果: