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

标签 java swing opencv

我有这个源代码,它可以在 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/

相关文章:

python - openCV2无法正确显示图像(添加了灰色区域)

java - 泰坦有远程服务器吗?

java - 使用使用 java.beans 类(Introspector、BeanInfo 或 PropertyDescriptor)的 jar

java - 哪个Java IDE有像Visual Studio这样的工具箱?

java - 为什么循环没有完成它的工作?

java - 为什么 JButton 的图片又出现在顶部?

java - Swing 应用程序窗口在 Mac 上没有响应

java - 如何使用 Jtable 中该行中第一个单元格的单元格编辑器编辑一行中的所有单元格?

opencv - Findcontours 检索未分类的轮廓

matlab - matlab的opencv模块无法正常工作