How to show image in Java using OpenCV

Hello everyone! here we will learn about how to show or display an image in Java using OpenCV. In order to read and display an image, you need to download the “OpenCV” library from the internet and set its environmental variable path. Follow certain steps to link these libraries to your program.

  1. open your source code.
  2. right-click on your java file.
  3. select the build path option.
  4. select configure build path option.
  5. Click on libraries option in the window.
  6.  select add external libraries jars.
  7. select the folder in which you added the OpenCV library.
  8. add the native library path.

Learn how to display an image in Java using OpenCV

package jyothi;

import java.awt.image.BufferedImage;


import javax.imageio.ImageIO;
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.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;

public class core {
   public static void main(String args[]) throws Exception { 
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); 
      String f = "C:/b.jpg"; 
      Mat img = Imgcodecs.imread(f); 
      MatOfByte mat = new MatOfByte();       
      Imgcodecs.imencode(".jpg", img, mat); 
      byte[] byteArray = mat.toArray(); 
      InputStream in = new ByteArrayInputStream(byteArray); 
      BufferedImage buf =; 
      JFrame fr = new JFrame(); 
      fr.getContentPane().add(new JLabel(new ImageIcon(buf))); 
      System.out.println("Image Loaded");     

Firstly import all the OpenCV packages required. Then load the native library by “loadLibrary” method. Then store the “file-path” in a string. Create a Mat object and read the file. In order to display the image,  here we are using  J frames. And we are making it visible by “setVisible”.

So, that’s how we can display images. I hope it is clear about the code that is explained above to show image in Java using OpenCV.

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *