OpenCV_webcam4.java
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.videoio.VideoCapture;
public class OpenCV_webcam4 {
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
static JLabel lblNewLabel = new JLabel("");
public static void main(String[] args) {
VideoCapture camera = null;
camera = initCamera();
JFrame layoutFrame = new JFrame();
layoutFrame = layout();
if(camera.isOpened()) {
Mat webcam_frame = new Mat();
camera.read(webcam_frame);
layoutFrame.setSize(webcam_frame.width()+40,webcam_frame.height()+60);
while(true) {
camera.read(webcam_frame);
BufferedImage frameImage = matToBufferedImage(webcam_frame);
lblNewLabel.setIcon(new ImageIcon(frameImage));
}
}else {
System.out.println("Error!!");
}
}
private static VideoCapture initCamera() {
VideoCapture capturecCapture = new VideoCapture();
capturecCapture.open(0);
return capturecCapture;
}
private static JFrame layout() {
JFrame frame1 = new JFrame("");
frame1.setTitle("從 webcam 讀 讀 讀 讀");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(672, 480);
frame1.setBounds(0,0,frame1.getWidth()+10,frame1.getHeight()+10);
lblNewLabel.setBounds(21,23,571,413);
frame1.add(lblNewLabel);
frame1.setVisible(true);
return frame1;
}
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 rgb
byte 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;
}
}
Recommended Posts