java-opencv Image和Mat相互转换

安装opencv

导入jar包需要dll

Image转换成Mat

package opencv;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class Test7 {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);//加载库,否则会出错
    }

    public static void main(String[] args) throws IOException {
        Image i = ImageIO.read(new File("D:\\1.png"));//Image图片
        Mat m = new Mat(((BufferedImage) i).getHeight(), ((BufferedImage) i).getWidth(), CvType.CV_8UC3);//Mat图片
        DataBuffer d = ((BufferedImage) i).getRaster().getDataBuffer();//获取输入流
        byte[] b = ((DataBufferByte) d).getData();//Image转换成二进制数据
        m.put(0, 0, b);//二进制数据转换成Mat
        Imgcodecs.imwrite("D:\\2.png", m);
    }

}

结果

Image(1.png)被转换成Mat后写入2.png,两张图片无区别

Mat转换成Image

package opencv;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.*;

public class Test8 {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);//加载库,否则会出错
    }

    public static void main(String[] args) throws IOException {
        Mat m = Imgcodecs.imread("D:\\1.png");//Mat图片
        Image i;//Image图片
        MatOfByte b = new MatOfByte();//保存的二进制数据
        Imgcodecs.imencode(".png", m, b);//Mat转换成二进制数据。.png表示图片格式,格式不重要,基本不会对程序有任何影响。
        i = ImageIO.read(new ByteArrayInputStream(b.toArray()));//二进制数据转换成Image
        ImageIO.write((RenderedImage) i, "png", new File("D:\\2.png"));
    }

}

结果

Mat(1.png)被转换成Image后写入2.png,两张图片无区别

你可能感兴趣的:(java-jar包,opencv,人工智能,计算机视觉,java,jar)