如何在Java中显示OpenCV图像?

时间:2016-01-12 13:47:48

标签: java opencv

有时需要在开发计算机视觉OpenCV Mat images应用程序时显示Java。 那么如何在OpenCV Mat images中显示这些Java

1 个答案:

答案 0 :(得分:0)

这是我为此创建的代码的要点: https://gist.github.com/fernandoc1/c5105070fa6acf2d0128

import org.opencv.core.*;
import org.opencv.highgui.*;
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;

public class DisplayImage
{
    static
    {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static BufferedImage Mat2BufferedImage(Mat m)
    {
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (m.channels() > 1)
        {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        int bufferSize = m.channels()*m.cols()*m.rows();
        byte[] b = new byte[bufferSize];
        m.get(0, 0, b); // get all the pixels
        BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        System.arraycopy(b, 0, targetPixels, 0, b.length);  
        return image;
    }

    public static void displayImage(Image img)
    {   
        ImageIcon icon = new ImageIcon(img);
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());        
        frame.setSize(img.getWidth(null)+50, img.getHeight(null)+50);     
        JLabel lbl = new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args)
    {
        System.out.println(args[0]);
        Mat m = Highgui.imread(args[0]);
        BufferedImage bi = Mat2BufferedImage(m);
        displayImage(bi);
    }
}

编译并运行:

all:
    javac -cp "/usr/share/OpenCV/java/opencv-248.jar" DisplayImage.java

run:
    LD_LIBRARY_PATH=/usr/lib/jni/ java -cp /usr/share/OpenCV/java/opencv-248.jar:. DisplayImage /path/to/image.png

在Ubuntu 14.04 64bit

中进行了测试