Capture video in OPENCV

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
stopflag = 1;
System.loadLibrary(“opencv_java300”);
vc = new VideoCapture(0);

Thread t = new Thread(){
@Override
public void run() {

while (true) {
if (vc.isOpened()) {
Mat m = new Mat();
vc.read(m);
ImageIcon i = new ImageIcon(Mat2bufferedImage(m));
jLabel3.setIcon(i);
jLabel3.repaint();

if (stopflag == 0) {
vc.release();
break;
}
} else {

System.err.println(“Cam Error”);
}
}

};
};
t.start();

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

stopflag = 0;
System.exit(0);
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate=”collapsed” desc=” Look and feel setting code (optional) “>
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (“Nimbus”.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CamCapture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CamCapture().setVisible(true);
}
});
}

// Variables declaration – do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration

private BufferedImage Mat2bufferedImage(Mat m) {
MatOfByte bytemat = new MatOfByte();
Imgcodecs.imencode(“.jpg”, m, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = null;
try {
img = ImageIO.read(in);
} catch (Exception e) {
e.printStackTrace();
}
return img;
}
}

Share Post