gpt4 book ai didi

java - 将 Mat 中的图像转换为 BufferedImage

转载 作者:太空宇宙 更新时间:2023-11-03 22:05:04 25 4
gpt4 key购买 nike

我有这个源代码,它可以在 Mat 中为 OpenCv 打开图像,然后执行一些操作,然后 bufferedImage 应该将它转换为图像,以便它可以在 JFrame 中显示。但我不知道如何传递参数。

public class objectDetection{


public void getMatImg(){

Mat imageInMat = Imgcodecs.imread(getClass().getResource("lena.png").getPath());
}

/*
*
* OpenCV code
*/


public static BufferedImage bufferedImage(Mat m) {


int type = BufferedImage.TYPE_BYTE_GRAY;
if (m.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);

m.get(0, 0, ((DataBufferByte)image.getRaster().getDataBuffer()).getData());
return image;

}

最佳答案

这是我们不久前为 2.4.8 或 .9 使用的一些代码。让我知道它是否适合您。

我认为当我们尝试传入一个现有的 BufferedImage 时可能遇到了一些问题,但如果您为 BufferedImage 传入 null 它工作正常。

/**  
* Converts/writes a Mat into a BufferedImage.
*
* @param matrix Mat of type CV_8UC3 or CV_8UC1
* @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
*/
public static BufferedImage matToBufferedImage(Mat matrix, BufferedImage bimg)
{
if ( matrix != null ) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int)matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for(int i=0; i<data.length; i=i+3) {
b = data[i];
data[i] = data[i+2];
data[i+2] = b;
}
break;
default:
return null;
}

// Reuse existing BufferedImage if possible
if (bimg == null || bimg.getWidth() != cols || bimg.getHeight() != rows || bimg.getType() != type) {
bimg = new BufferedImage(cols, rows, type);
}
bimg.getRaster().setDataElements(0, 0, cols, rows, data);
} else { // mat was null
bimg = null;
}
return bimg;
}

关于java - 将 Mat 中的图像转换为 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30262834/

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