2014-02-12 453 views
2

我试过这个link并且有下面的代码。我的程序以BufferedImage格式导入图像,然后将其显示给用户。我在OpenCV中使用matchingTemplate函数,这需要我将其转换为Mat格式。在Java中将BufferedImage转换为Mat(OpenCV)

如果我导入图像 - >将其转换为Mat,然后使用imwrite保存图像,则该代码有效。该程序还允许用户裁剪图像,然后使用Template matching将其与其他图像进行比较。问题来了,当我试图裁剪后的图像转换成太,我需要它转换为int使用此代码字节:

im = new BufferedImage(im.getWidth(), im.getHeight(),BufferedImage.TYPE_3BYTE_BGR); 

然而,这导致黑色图像。但是,如果我摆脱它,它只适用于导入的图像,而不是裁剪。这里发生了什么?我确信这是与coverion流程有关的,因为我已经使用读入图像测试了模板匹配功能。

// Convert image to Mat 
public Mat matify(BufferedImage im) { 
    // Convert INT to BYTE 
    //im = new BufferedImage(im.getWidth(), im.getHeight(),BufferedImage.TYPE_3BYTE_BGR); 
    // Convert bufferedimage to byte array 
    byte[] pixels = ((DataBufferByte) im.getRaster().getDataBuffer()) 
      .getData(); 

    // Create a Matrix the same size of image 
    Mat image = new Mat(im.getHeight(), im.getWidth(), CvType.CV_8UC3); 
    // Fill Matrix with image values 
    image.put(0, 0, pixels); 

    return image; 

} 

回答

1

你可以试试这个方法,实际上将图像转换为TYPE_3BYTE_BGR(你的代码只需创建相同大小的空白图像,这就是为什么它是黑色的)。

用法:

// Convert any type of image to 3BYTE_BGR 
im = toBufferedImageOfType(im, BufferedImage.TYPE_3BYTE_BGR); 

// Access pixels as in original code 

和转换方法:

public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) { 
    if (original == null) { 
     throw new IllegalArgumentException("original == null"); 
    } 

    // Don't convert if it already has correct type 
    if (original.getType() == type) { 
     return original; 
    } 

    // Create a buffered image 
    BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type); 

    // Draw the image onto the new buffer 
    Graphics2D g = image.createGraphics(); 
    try { 
     g.setComposite(AlphaComposite.Src); 
     g.drawImage(original, 0, 0, null); 
    } 
    finally { 
     g.dispose(); 
    } 

    return image; 
} 
+0

谢谢,结束了在OpenCV中的垫格式工作然后将它转换一个BufferedImage显示给用户,这需要大量的重新工作的方法。但是当我有机会时,我会试试这个。 – user2916314

+0

'pOriginal'应该是'original'吗? –

+0

@Sortofabeginner:是的,发现很好。 :-) 谢谢。现在编辑。 – haraldK