Skip to content
Related Articles

Related Articles

Taking a Snapshot from System Camera using OpenCV in Java
  • Last Updated : 13 Jan, 2021

The OpenCV library in Java contains a class named ‘VideoCapture’ which provides a method called read (which is predefined) to scan pictures from the webcam. Mat object is passed as a parameter in the read method.

Concept: 

  1. The ‘javax.swing’ Package
  2. The Abstract Window Toolkit (AWT)

Let’s discuss them briefly before diving into the procedure and implementation part.

  • The ‘javax.swing’ package is used as this package provides classes for Java Swing API such as JButton, JTextArea, JCheckbox, JMenu, etc. Concepts of java involved here are Swing class and abstract windows toolkit as mentioned below:
    • javax.swing.ImageIcon : The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
    • javax.swing.Jframe : The class JFrame is a type of container which inherits the java. JFrame works like the main window where components like labels, buttons, text fields are added to create a GUI.
    • javax.swing.JLabel : The class JLabel is used to display a short string or an image icon.x
  • The Abstract Window Toolkit (AWT) is a Java package used for creating graphical user interfaces. AWT features include:
    • A set of native interface components.
    • A robust event-handling model.
    • Graphics and imaging tools, including shape, color, and font classes.
    • Layout managers, for flexible window layouts that do not depend on a particular window size or screen resolution.
    • Data transfer classes, for cut and paste through the native platform clipboard.

Procedure: Steps to draw geometric shapes on images in OpenCV

  1. Create a project and add an OpenCV library.
  2. Create Package
  3. Create a Class
  4. Create a folder named “images” to save the captured images.
  5. Writing the desired java program to a java file.

Implementation: Writing the following java program in the java file to take a snapshot from the system camera.



Example

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to take a Snapshot from System Camera
// using OpenCV
  
// Importing openCV modules
package com.opencvcamera;
// importing swing and awt classes
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Importing date class of sql package
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
// Importing VideoCapture class
// This class is responsible for taking screenshot
import org.opencv.videoio.VideoCapture;
  
// Class - Swing Class
public class Camera extends JFrame {
  
    // Camera screen
    private JLabel cameraScreen;
  
    // Button for image capture
    private JButton btnCapture;
  
    // Start camera
    private VideoCapture capture;
  
    // Store image as 2D matrix
    private Mat image;
  
    private boolean clicked = false;
  
    public Camera()
    {
  
        // Designing UI
        setLayout(null);
  
        cameraScreen = new JLabel();
        cameraScreen.setBounds(0, 0, 640, 480);
        add(cameraScreen);
  
        btnCapture = new JButton("capture");
        btnCapture.setBounds(300, 480, 80, 40);
        add(btnCapture);
  
        btnCapture.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e)
            {
  
                clicked = true;
            }
        });
  
        setSize(new Dimension(640, 560));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
  
    // Creating a camera
    public void startCamera()
    {
        capture = new VideoCapture(0);
        image = new Mat();
        byte[] imageData;
  
        ImageIcon icon;
        while (true) {
            // read image to matrix
            capture.read(image);
  
            // convert matrix to byte
            final MatOfByte buf = new MatOfByte();
            Imgcodecs.imencode(".jpg", image, buf);
  
            imageData = buf.toArray();
  
            // Add to JLabel
            icon = new ImageIcon(imageData);
            cameraScreen.setIcon(icon);
  
            // Capture and save to file
            if (clicked) {
                // prompt for enter image name
                String name = JOptionPane.showInputDialog(
                    this, "Enter image name");
                if (name == null) {
                    name = new SimpleDateFormat(
                               "yyyy-mm-dd-hh-mm-ss")
                               .format(new Date(
                                   HEIGHT, WIDTH, getX()));
                }
  
                // Write to file
                Imgcodecs.imwrite("images/" + name + ".jpg",
                                  image);
  
                clicked = false;
            }
        }
    }
  
    // Main driver method
    public static void main(String[] args)
    {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        EventQueue.invokeLater(new Runnable() {
            // Overriding existing run() method
            @Override public void run()
            {
                final Camera camera = new Camera();
  
                // Start camera in thread
                new Thread(new Runnable() {
                    @Override public void run()
                    {
                        camera.startCamera();
                    }
                }).start();
            }
        });
    }
}

chevron_right


Output:

After a successful compilation of the program, the execution is as follows as the webcam will open up where you click on the “Capture” button and the rest image will be named. Now, click on the “OK” button to save the image. The output image will be saved in the folder which was created earlier.


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :