Java Program to Draw Geometric Shapes on Images in OpenCV
Last Updated :
03 Jan, 2023
The OpenCV library in Java contains a class named Imgproc which provides various methods such as resize(), wrapAffine( ), filter2D to process an input image. We will use the javax.swing package here. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser, etc. Concepts of java involved here are Swing class and abstract windows toolkit as mentioned below:
Swing Class: Here I will explain all the classes of the javax.swing package which will be used in the program later:
- 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, textfields are added to create a GUI
- javax.swing.JLabel : The class JLabel is used to display a short string or an image icon.
- javax.swing.JMenu : The class JMenu is used to pull down menu  component which is displayed from the menubar.
- javax.swing.JMenuBar : The class JMenuBar is used to display menubar on the window or frame. It may have several menus.
- javax.swing.JMenuItem : The JMenuItem class represents the actual item in a menu. All items in a menu should derive from class JMenuItem, or one of its subclasses.
We also need to use the Abstract Window Toolkit (AWT) in the program. It is part of the Java Foundation Classes (JFC). I will briefly describe AWT here.Â
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
- Create a project and add OpenCV library
- Create Package
- Create a Class
- Create a folder named "images" and put a .jpg or .png file in it.
- Write the following code in the java file.
Sample Input Image:
Step 1: Create a project and add OpenCV library
- Click on File> New > Java Project.
- Give a name to your project and checkmark the necessary options under the JRE and Project Layout options as shown below in the figure. Here, I have named the project OpenCVShape.
- After marking the options click on Next.

- After that go to the Libraries option in the same dialogue box. Click on classpath -> Add external jars.
- Add the opencv.jar file from your local machine or can be download opencv.jar file.

- After adding the jar file, expand the Classpath option, and click on Native library location: (None), and click on Edit.

- Select External Folder... and browse to select the folder containing the OpenCV libraries (e.g., C:\opencv\build\java\x64 under Windows). Click on Finish.
Step 2: Create Package
- Right-click on src. Go to New → Package.
- A dialog box will appear. Type the name of the package as com.pkg and click on Finish.
Step 3: Create a Class
- Right-click on com.pkg. Go to new → Class.
- A dialog box will appear. Type the name of the class. I have named it OpenCVShape.
- Checkmark the necessary options and click on Finish.
Step 4: Create a folder named "images" and put a .jpg or .png file in it.
- Right-click on the name of your project (in this case OpenCVShape). Go to New -> Folder. Type the name of the folder (images) and click OK.
- Put an image with extension .jpg or .png in this folder.
Step 5: Write the following code in the java file
Implementation: The above steps are computed to get different geometric shapes as shown in examples below:Â
- Line
- Rectangles
- Circles
- Ellipses
Example 1: Drawing LinesÂ
Java
// Java Program using openCV to draw lines
package com.pkg;
// Importing abstract windows toolkit classes
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
// Importing Swing classes
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
// Importing OpenCV modules
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class OpenCVShapes extends JFrame {
Mat image;
Mat tempImage;
JLabel imageView;
// Menu for save image
private JMenuBar mb;
private JMenu menu;
private JMenuItem saveMenuItem;
private Point originPoint;
public OpenCVShapes()
{
// Loading image from local directory
image = Imgcodecs.imread("images/sample_image.png");
// Method to view setup
setUpView();
// Loading image to jlabel
loadImage(image);
// Setting iframe property
setSize(image.width(), image.height());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// Method to load image
private void loadImage(Mat img)
{
final MatOfByte mof = new MatOfByte();
Imgcodecs.imencode(".png", img, mof);
final byte[] imageData = mof.toArray();
// Change image byte to image icon
final ImageIcon icon = new ImageIcon(imageData);
// Add icon to jlabel
imageView.setIcon(icon);
}
private void setUpView()
{
setLayout(null);
imageView = newJLabel();
imageView.setBounds(0, 20, image.width(),
image.height());
// Add mouse listener
imageView.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
// Storing location of mouse pressed
originPoint = new Point(e.getX(), e.getY());
}
@Override
public void mouseReleased(MouseEvent e)
{
super.mouseReleased(e);
// when mouse release replace tempimage to
// image
image = tempImage.clone();
}
});
// Adding another event mousemotionlistener
imageView.addMouseMotionListener(
new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e)
{
// TODO Auto-generate method stub
}
@Override
public void mouseDragged(MouseEvent e)
{
// Create temp image for drawing
tempImage = image.clone();
final Point point
= new Point(e.getX(), e.getY());
// NOW, DRAWING SHAPES
// 1. Drawing line
// Color in bgr format
Imgproc.line(
tempImage, originPoint, point,
new Scalar(0, 0, 0),
5);
loadImage(tempImage);
}
});
add(imageView);
// Adding menu
mb = new JMenuBar();
menu = new JMenu("file");
saveMenuItem = new JMenuItem("save");
menu.add(saveMenuItem);
mb.add(menu);
mb.setBounds(0, 0, image.width(), 20);
add(mb);
saveMenuItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
Imgcodecs.imwrite("images/ind1.png",
image);
}
});
}
private JLabel newJLabel()
{
// TODO Auto-generated method stub
return null;
}
// Main driver method
public static void main(String[] args)
{
// Loading library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
EventQueue.invokeLater(new Runnable() {
@Override public void run()
{
new OpenCVShapes();
}
});
}
}
Â
Â
Output:
Â
Â
Example 2: Drawing rectangles
Â
Java
// Java Program using openCV to draw rectangles
package com.pkg;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class OpenCVShapes extends JFrame {
Mat image;
Mat tempImage;
JLabel imageView;
// menu for save image
private JMenuBar mb;
private JMenu menu;
private JMenuItem saveMenuItem;
private Point originPoint;
public OpenCVShapes()
{
// load image
image = Imgcodecs.imread("images/sample_image.png");
// view setup
setUpView();
// load image to jlabel
loadImage(image);
// set iframe property
setSize(image.width(), image.height());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void loadImage(Mat img)
{
final MatOfByte mof = new MatOfByte();
Imgcodecs.imencode(".png", img, mof);
final byte[] imageData = mof.toArray();
// change image byte to image icon
final ImageIcon icon = new ImageIcon(imageData);
// add icon to jlabel
imageView.setIcon(icon);
}
private void setUpView()
{
setLayout(null);
imageView = newJLabel();
imageView.setBounds(0, 20, image.width(),
image.height());
// add mouse listener
imageView.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
// store location of mouse pressed
originPoint = new Point(e.getX(), e.getY());
}
@Override
public void mouseReleased(MouseEvent e)
{
super.mouseReleased(e);
// when mouse release replace tempimage to
// image
image = tempImage.clone();
}
});
// add another event mousemotionlistener
imageView.addMouseMotionListener(
new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e)
{
// TODO Auto-generate method stub
}
@Override
public void mouseDragged(MouseEvent e)
{
// create temp image for drawing
tempImage = image.clone();
final Point point
= new Point(e.getX(), e.getY());
// here we will draw shapes
// draw rectangle
Imgproc.rectangle(
tempImage, originPoint, point,
new Scalar(255, 0, 0), 5);
loadImage(tempImage);
}
});
add(imageView);
// add menu
mb = new JMenuBar();
menu = new JMenu("file");
saveMenuItem = new JMenuItem("save");
menu.add(saveMenuItem);
mb.add(menu);
mb.setBounds(0, 0, image.width(), 20);
add(mb);
saveMenuItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
Imgcodecs.imwrite("images/ind1.png",
image);
}
});
}
private JLabel newJLabel()
{
// TODO Auto-generated method stub
return null;
}
// main driver method
public static void main(String[] args)
{
// Loading library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
EventQueue.invokeLater(new Runnable() {
@Override public void run()
{
new OpenCVShapes();
}
});
}
}
Â
Â
Output:
Â
Â
Example 3: Drawing circles
Â
Java
// Java Program using openCV to draw circles
package com.pkg;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class OpenCVShapes extends JFrame {
Mat image;
Mat tempImage;
JLabel imageView;
// menu for save image
private JMenuBar mb;
private JMenu menu;
private JMenuItem saveMenuItem;
private Point originPoint;
public OpenCVShapes()
{
// load image
image = Imgcodecs.imread("images/sample_image.png");
// view setup
setUpView();
// load image to jlabel
loadImage(image);
// set iframe property
setSize(image.width(), image.height());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void loadImage(Mat img)
{
final MatOfByte mof = new MatOfByte();
Imgcodecs.imencode(".png", img, mof);
final byte[] imageData = mof.toArray();
// change image byte to image icon
final ImageIcon icon = new ImageIcon(imageData);
// add icon to jlabel
imageView.setIcon(icon);
}
private void setUpView()
{
setLayout(null);
imageView = newJLabel();
imageView.setBounds(0, 20, image.width(),
image.height());
// add mouse listener
imageView.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
// store location of mouse pressed
originPoint = new Point(e.getX(), e.getY());
}
@Override
public void mouseReleased(MouseEvent e)
{
super.mouseReleased(e);
// when mouse release replace tempimage to
// image
image = tempImage.clone();
}
});
// add another event mousemotionlistener
imageView.addMouseMotionListener(
new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e)
{
// TODO Auto-generate method stub
}
@Override
public void mouseDragged(MouseEvent e)
{
// create temp image for drawing
tempImage = image.clone();
final Point point
= new Point(e.getX(), e.getY());
// here we will draw shapes
// draw circle
// first find distance of origin point
// and point
double ab2
= Math.pow(originPoint.x - point.x,
2)
+ Math.pow(
originPoint.y - point.y, 2);
int distance = (int)Math.sqrt(ab2);
Imgproc.circle(
tempImage, originPoint, distance,
new Scalar(0, 255, 0), 5);
loadImage(tempImage);
}
});
add(imageView);
// add menu
mb = new JMenuBar();
menu = new JMenu("file");
saveMenuItem = new JMenuItem("save");
menu.add(saveMenuItem);
mb.add(menu);
mb.setBounds(0, 0, image.width(), 20);
add(mb);
saveMenuItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
Imgcodecs.imwrite("images/ind1.png",
image);
}
});
}
private JLabel newJLabel()
{
// TODO Auto-generated method stub
return null;
}
// Main driver method
public static void main(String[] args)
{
// Loading library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
EventQueue.invokeLater(new Runnable() {
@Override public void run()
{
new OpenCVShapes();
}
});
}
}
Â
Â
Output:
Â
Â
Example 4: Drawing ellipses
Â
Java
// Java Program using openCV to draw ellipses
package com.pkg;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class OpenCVShapes extends JFrame {
Mat image;
Mat tempImage;
JLabel imageView;
// menu for save image
private JMenuBar mb;
private JMenu menu;
private JMenuItem saveMenuItem;
private Point originPoint;
public OpenCVShapes()
{
// load image
image = Imgcodecs.imread("images/sample_image.png");
// view setup
setUpView();
// load image to jlabel
loadImage(image);
// set iframe property
setSize(image.width(), image.height());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void loadImage(Mat img)
{
final MatOfByte mof = new MatOfByte();
Imgcodecs.imencode(".png", img, mof);
final byte[] imageData = mof.toArray();
// change image byte to image icon
final ImageIcon icon = new ImageIcon(imageData);
// add icon to jlabel
imageView.setIcon(icon);
}
private void setUpView()
{
setLayout(null);
imageView = newJLabel();
imageView.setBounds(0, 20, image.width(),
image.height());
// add mouse listener
imageView.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
// store location of mouse pressed
originPoint = new Point(e.getX(), e.getY());
}
@Override
public void mouseReleased(MouseEvent e)
{
super.mouseReleased(e);
// when mouse release replace tempimage to
// image
image = tempImage.clone();
}
});
// add another event mousemotionlistener
imageView.addMouseMotionListener(
new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e)
{
// TODO Auto-generate method stub
}
@Override
public void mouseDragged(MouseEvent e)
{
// create temp image for drawing
tempImage = image.clone();
final Point point
= new Point(e.getX(), e.getY());
// here we will draw shapes
// draw eclipse
double x
= Math.abs(point.x - originPoint.x);
double y
= Math.abs(point.y - originPoint.y);
Size size = new Size(x * 2, y * 2);
Imgproc.ellipse(
tempImage,
new RotateRect(originPoint, size,
0),
new Scalar(255, 255, 0), 5);
loadImage(tempImage);
}
});
add(imageView);
// add menu
mb = new JMenuBar();
menu = new JMenu("file");
saveMenuItem = new JMenuItem("save");
menu.add(saveMenuItem);
mb.add(menu);
mb.setBounds(0, 0, image.width(), 20);
add(mb);
saveMenuItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
Imgcodecs.imwrite("images/ind1.png",
image);
}
});
}
private JLabel newJLabel()
{
// TODO Auto-generated method stub
return null;
}
// Main driver method
public static void main(String[] args)
{
// Loading library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
EventQueue.invokeLater(new Runnable() {
@Override public void run()
{
new OpenCVShapes();
}
});
}
}
Â
Â
Output:Â
Â
Â
Similar Reads
Java Program to Add Text to an image in OpenCV
OpenCV is the cross-platform open-source library for computer vision, image processing, and machine learning. Â It plays a major role nowadays in real-time operations in improving modules provides adequate functions for image manipulation. It has C++, C, Python, and Java interfaces and supports Windo
3 min read
Java Program to Copy and Paste an image in OpenCV
OpenCV is a Machine Learning and open-source computer vision software library, the main purpose for which it was developed is to enable a common medium to increase the use of machine perception in commercial businesses and accelerate the development of computer vision applications, it is a smooth an
3 min read
Java OpenCV Programs - Basic to Advanced
Java is a popular programming language that can be used to create various types of applications, such as desktop, web, enterprise, and mobile. Java is also an object-oriented language, which means that it organizes data and behaviour into reusable units called classes and objects. Java is known for
2 min read
Java Program to Blur Images using OpenCV
Blurring is a simple and frequently used image processing operation. It is also called as Smoothing. OpenCV library provides many functions to apply diverse linear filters to smooth images or blur images. Smoothing of an image removes noisy pixels from the image and applying a low-pass filter to an
4 min read
Java Program to Convert PNG Images to JPEG
PNG and JPG formats are used for image illustrations. Both the formats are used to provide good compatibilities with certain types of images like PNG works better with line drawings and icon graphics whereas JPG works well with photographs. However, both are interconvertible with respect to each oth
4 min read
Java Program to Draw a Shape in Excel Sheet using Apache POI
Apache POI supports customized printing by allowing users to select a range of cells in order to configure the desired print area in a worksheet using Java Program. The top-most shape is the patriarch. This is not visible on the sheet at all. To start drawing you need to call createPatriarch on the
4 min read
Java Program to Convert Byte Array to Image
A byte array is the array of bytes that is used to store the collection of binary data. For example, the byte array of an image stores the information of every pixel of the image. In the byte array, we can store the content of any file in binary format. We can initialize the byte array with the byte
3 min read
Java Program to Rotate an Image
The problem statement is to rotate an image clockwise 90 degrees for which here we will be using some in-built methods of BufferedImage class and Color c Classes required to perform the operation is as follows: To read and write an image file we have to import the File class. This class represents f
3 min read
Rotating Images using OpenCV in Java
Image rotation is a common image processing routine used to rotate images at any desired angle. This helps in image reversal, flipping, and obtaining an intended view of the image. Image rotation has applications in matching, alignment, and other image-based algorithms. OpenCV is a well-known librar
6 min read
Java Program to Implement Bowyer-Watson Algorithm
To gain some practical programming experience related to computational geometry topics, we will apply the Bowyer-Watson algorithm that will be able to facilitate the process to some extent. Bowyer-Watson AlgorithmThe Bowyer-Watson algorithm is a computational algorithm for constructing Delaunay tria
4 min read