gpt4 book ai didi

java - 使用java在openCV中使用Mat

转载 作者:行者123 更新时间:2023-12-01 10:21:08 25 4
gpt4 key购买 nike

在openCV中使用Mat类的正确方法是什么(使用java)

Mat Class ==> org.opencv.core.Mat and do I have to use BufferedImage when I want to read image into Mat. please show me Code answer

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.opencv.core.*;

public class opencv {

public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedImage img1 = null, img2 = null;
try {
img1 = ImageIO.read(new File("c:\\test.jpg"));
// img1 = ImageIO.read(new File("c:\\Fig2.tif"));
System.out.print(img1.getHeight());
} catch (IOException e) {
}

//byte[] pxl1 = ((DataBufferByte) img1.getRaster()).getData();
//Mat src1 = new Mat("");
//Core.addWeighted(Mat1, alpha, Mat2, beta, gamma, dst);

}

}

最佳答案

假设您的图像是 3 channel :

public Mat fromBufferedImage(BufferedImage img) {
byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
mat.put(0, 0, pixels);
return mat;
}

反之亦然:

public BufferedImage toBufferedImage(Mat mat) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if (mat.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
byte[] bytes = new byte[mat.channels() * mat.cols() * mat.rows()];
mat.get(0, 0, bytes);
BufferedImage img = new BufferedImage(mat.cols(), mat.rows(), type);
final byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
System.arraycopy(bytes, 0, pixels, 0, bytes.length);
return img;
}

关于java - 使用java在openCV中使用Mat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35612073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com