2016-10-22 89 views
0

這似乎是「已經回答」的話題的次數太多了,但我仍然無法找到一個可行的解決方案。我需要用JavaCV序列化IplImages和Mats。我不能使用文件系統,我必須堅持使用JavaCV 1.2/JavaCPP 1.2.4/OpenCV 3.1(注意:我不能使用OpenCV自己的Java包裝 - 我必須使用JavaCV)。我在Stackoverflow上發現了許多建議,但它們都是:1)使用不推薦的方法,或2)使用不再存在的方法。我知道IplImages和Mats很容易互換,所以一個解決方案適用於另一個。理想的解決方案將是一種將IplImage/Mat轉換爲字節數組並返回的方法。我希望你們能幫忙。IplImage/Mat到字節數組,回到JavaCV 1.2

回答

0

我有最新的JavaCV解決方案。實際上,有幾個。我遇到了一些圖像的麻煩,所以我第二次嘗試轉換爲字節數組產生了更一致的結果。 這裏的解決方案在斯卡拉。

要轉換爲包含圖像數據的字節數組,您需要獲取字節。

Mat m = new Mat(iplImage); 
ByteBuffer buffer = this.image.asByteBuffer(); 
Mat m = new Mat(this.image); 
int sz = (m.total() * m.channels()); 
byte[] barr = new byte[sz](); 
m.data().get(barr); 

轉換爲java.nio.ByteBuffer中,使用從圖像的總大小(我轉換成墊),並獲得數據。我忘記了m.total * m.channels是否返回double,long,int或float。我在斯卡拉使用.toInt。

另一種選擇是使用BufferedImage。我的一些圖像使用JavaCV出現了一些奇怪的現象。

BufferedImage im = new Java2DFrameConverter().convert(new OpenCVFrameConverter.ToIplImage().convert(this.image)) 
BytearrayOutputstream baos = new ByteArrayOutputStream(); 
byte[] barr = null; 
try{ 
    ImageIO.write(im,"jpg",baos); 
    baos.flush(); 
    barr = baos.toByteArray(); 
}finally{ 
    baos.close(); 
} 
//This could be try with resources but the original was in Scala. 

要從字節數組轉換爲IplImage,實際上我使用緩衝圖像的可靠性。

ImplImage im = null; 
InputStream in = new ByteArrayInputStream(bytes); 
try { 
    Mat m = new Mat(image.getHeight,image.getWidth,image.getType,new BytePointer(ByteBuffer.wrap(image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData))); 
    im = new IplImage(m); 
}finally{ 
    in.close(); 
} 
//Again this could be try with resources but the original example was in Scala 
+0

這正是我一直在尋找的,除了我在Scala上完全不識字。任何人都會打擾在Java中重新編碼? – lcofresi

+0

給我一分鐘。將會有2個。這來自我的回購https://github.com/SimplrTek/GoatImaging2 –

+0

@Icofresi轉換非常簡單。我爲你留下了一些筆記。 JavaCV示例使用Scala,因爲它可以在編譯JVM字節碼時與Java庫進行交互。 –