ImageからFile
fun run(image: android.media.Image, file: File) {
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.remaining())
buffer.get(bytes)
var output: FileOutputStream? = null
try {
output = FileOutputStream(file).apply {
write(bytes)
}
} catch (e: IOException) {
Log.e(TAG, e.toString())
} finally {
image.close()
output?.let {
try {
it.close()
} catch (e: IOException) {
Log.e(TAG, e.toString())
}
}
}
}
- imageはJPEGの場合
-
image.planes[0].bufferでByteBufferを取得する。 - ByteArrayで必要なバイト列をとって、ファイルに書き出している。
ImageからMat
Image image = reader.acquireLatestImage();
Mat buf = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1);
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
buf.put(0, 0, bytes);
Mat mat = Imgcodecs.imdecode(buf, IMREAD_COLOR);
image.close();
- ImageはJPEG形式の想定
- imageのheight/widthでMatを初期化する。
- CV_8UC1は8bit,unsighed,1チャンネル(グレースケール)の画像
- IMREAD_COLORはデフォルト値と同じ指定
ImageからMat(YUV)