2014-02-12 132 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