计算机系统应用教程网站

网站首页 > 技术文章 正文

Java,图像处理,OpenCV,JavaCV,BufferedImage与Mat格式转换

btikc 2024-09-04 03:19:55 技术文章 10 ℃ 0 评论

Java,java.awt.image.BufferedImage

Java,BufferedImage是Image的子类,用于处理和操纵图像数据,BufferedImage由图像数据的ColorModel组成,所有BufferedImage对象的左上角坐标为(0,0)。

代码案例1,BufferedImage图片:

package com.what21.image01.demo01;

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

public class ImageTest01 {

    public static void main(String[] args) throws Exception {
        BufferedImage image = ImageIO.read(new File("D:\\test.jpg"));
        System.out.println("image.width " + image.getWidth()); // 800
        System.out.println("image.height " + image.getHeight()); // 444
        Graphics2D g = (Graphics2D) image.getGraphics();
        Color color = new Color(123, 0, 35);
        g.setColor(color);
        Font font = new Font("宋体", Font.BOLD, 165);
        g.setFont(font);
        g.drawString("IT小奋斗", 40, 240);
        ImageIO.write(image, "jpg", new File("D:\\test-1.jpg"));
    }

}

效果:

代码案例2,JFrame中使用:

package com.what21.image01.demo01;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class ImageTest02 extends JPanel {

    public void paint(Graphics g) {
        Image img = createImageWithText();
        // 画图
        g.drawImage(img, 20, 20, this);
    }

    private Image createImageWithText() {
        BufferedImage bufferedImage = new BufferedImage(500, 300, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();
        Color color = new Color(123, 0, 123);
        g.setColor(color);
        Font font = new Font("宋体", Font.BOLD, 30);
        g.setFont(font);
        g.drawString("IT小奋斗", 20, 40);
        g.drawString("IT小奋斗", 20, 80);
        g.drawString("IT小奋斗", 20, 120);
        g.drawString("IT小奋斗", 20, 160);
        g.drawString("IT小奋斗", 20, 200);
        return bufferedImage;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new ImageTest02());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
}

Java,BufferedImage与OpenCV,org.opencv.core.Mat相互转换

代码案例:

package com.what21.opencv01.demo02;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class BufferedImageOpenCVDemo {

    static {
        // 保证先执行该语句,用于加载库
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static void main(String[] args) throws Exception {
        // OpenCV Mat 转换为 BufferedImage
        Mat source = Imgcodecs.imread("D:\\demo.jpg");
        BufferedImage image = BufferedImageOpenCVUtils.mat2BufferedImage(source);
        System.out.println("image.width " + image.getWidth());
        System.out.println("image.height " + image.getHeight());
        ImageIO.write(image, "jpg", new File("D:\\demo.1.jpg"));
        BufferedImage targetImage = BufferedImageOpenCVUtils.matToBufferedImage(source);
        ImageIO.write(image, "jpg", new File("D:\\demo.2.jpg"));

        // BufferedImage转换为 OpenCV Mat
        BufferedImage image2 = ImageIO.read(new File("D:\\demo.jpg"));
        Mat target = BufferedImageOpenCVUtils.bufferedImageToMat(image2);
        Imgcodecs.imwrite("D:\\demo.3.jpg", target);
        //
        Mat target2 = BufferedImageOpenCVUtils.img2Mat(image2);
        Imgcodecs.imwrite("D:\\demo.4.jpg", target2);
    }

}
package com.what21.opencv01.demo02;

import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.IOException;

public class BufferedImageOpenCVUtils {

    /**
     * @param matrix
     * @return
     * @throws IOException
     */
    public static BufferedImage mat2BufferedImage(Mat matrix) throws IOException {
        MatOfByte mob = new MatOfByte();
        Imgcodecs.imencode(".jpg", matrix, mob);
        return ImageIO.read(new ByteArrayInputStream(mob.toArray()));
    }

    /**
     * @param image
     * @return
     */
    public static Mat bufferedImageToMat(BufferedImage image) {
        Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
        byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        mat.put(0, 0, data);
        return mat;
    }

    /**
     * @param in
     * @return
     */
    public static Mat img2Mat(BufferedImage in) {
        Mat out;
        byte[] data;
        int r, g, b;
        if (in.getType() == BufferedImage.TYPE_INT_RGB) {
            out = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC3);
            data = new byte[in.getWidth() * in.getHeight() * (int) out.elemSize()];
            int[] dataBuff = in.getRGB(0, 0, in.getWidth(), in.getHeight(), null, 0, in.getWidth());
            for (int i = 0; i < dataBuff.length; i++) {
                data[i * 3] = (byte) ((dataBuff[i] >> 0) & 0xFF);
                data[i * 3 + 1] = (byte) ((dataBuff[i] >> 8) & 0xFF);
                data[i * 3 + 2] = (byte) ((dataBuff[i] >> 16) & 0xFF);
            }
        } else {
            out = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC1);
            data = new byte[in.getWidth() * in.getHeight() * (int) out.elemSize()];
            int[] dataBuff = in.getRGB(0, 0, in.getWidth(), in.getHeight(), null, 0, in.getWidth());
            for (int i = 0; i < dataBuff.length; i++) {
                r = (byte) ((dataBuff[i] >> 0) & 0xFF);
                g = (byte) ((dataBuff[i] >> 8) & 0xFF);
                b = (byte) ((dataBuff[i] >> 16) & 0xFF);
                data[i] = (byte) ((0.21 * r) + (0.71 * g) + (0.07 * b));
            }
        }
        out.put(0, 0, data);
        return out;
    }

    /**
     * @param frame
     * @return
     */
    public static BufferedImage matToBufferedImage(Mat frame) {
        int type = 0;
        if (frame.channels() == 1) {
            type = BufferedImage.TYPE_BYTE_GRAY;
        } else if (frame.channels() == 3) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        BufferedImage image = new BufferedImage(frame.width(), frame.height(), type);
        WritableRaster raster = image.getRaster();
        DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
        byte[] data = dataBuffer.getData();
        frame.get(0, 0, data);
        return image;
    }

}

Java,BufferedImage与JavaCV,org.bytedeco.javacpp.opencv_core.Mat相互转换

org.opencv.core.Mat与org.bytedeco.javacpp.opencv_core.Mat,两种Mat格式,两者不互通,导入的依赖包也不同,Mat格式转换先将org.opencv.core.Mat转化为java.awt.image.BufferedImage,再将BufferImage转化为org.bytedeco.javacpp.opencv_core.Mat格式。

代码案例:

package com.what21.javacv01.demo02;

import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.Java2DFrameUtils;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.opencv_core.Mat;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class BufferedImageJavaCVDemo {

    public static void main(String[] args) throws Exception {
        //  BufferedImage转换为JavaCV Mat
        BufferedImage image = ImageIO.read(new File("D:\\demo.jpg"));
        Mat mat1 = Java2DFrameUtils.toMat(image);
        opencv_imgcodecs.imwrite("D:\\demo_1.jpg", mat1);
        Mat mat2 = bufferedImageToMat(image);
        opencv_imgcodecs.imwrite("D:\\demo_2.jpg", mat2);
        //  JavaCV Mat转换为BufferedImage
        BufferedImage targetImage = Java2DFrameUtils.toBufferedImage(mat1);
        ImageIO.write(targetImage, "jpg", new File("D:\\demo_3.jpg"));
    }

    /**
     * @param bi
     * @return
     */
    public static Mat bufferedImageToMat(BufferedImage bi) {
        OpenCVFrameConverter.ToMat cv = new OpenCVFrameConverter.ToMat();
        return cv.convertToMat(new Java2DFrameConverter().convert(bi));
    }

}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表