Skip to content

Instantly share code, notes, and snippets.

@LiewJunTung
Created December 7, 2018 10:15
Show Gist options
  • Save LiewJunTung/e6f96c08347d3ba5d6c706d6a96fb40a to your computer and use it in GitHub Desktop.
Save LiewJunTung/e6f96c08347d3ba5d6c706d6a96fb40a to your computer and use it in GitHub Desktop.
Convert YUV to RGB from camera directly
package com.netvirta.curvecapturescanner
import android.graphics.ImageFormat
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicYuvToRGB
import android.renderscript.Type
import android.util.Log
import android.util.Size
import android.view.Surface
class RgbConversion(rs: RenderScript, private val mSizeVideoCall: Size) : Allocation.OnBufferAvailableListener {
private var mInputAllocation: Allocation? = null
private var mOutputAllocation: Allocation? = null
private val mScriptC: ScriptIntrinsicYuvToRGB
private val TAG = RgbConversion::class.java.simpleName
val inputSurface: Surface
get() = mInputAllocation!!.surface
init {
createAllocations(rs)
mInputAllocation!!.setOnBufferAvailableListener(this)
mScriptC = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))
}
private fun createAllocations(rs: RenderScript) {
val width = mSizeVideoCall.width
val height = mSizeVideoCall.height
val yuvTypeBuilder = Type.Builder(rs, Element.U8_4(rs))
yuvTypeBuilder.setX(width)
yuvTypeBuilder.setY(height)
yuvTypeBuilder.setYuvFormat(ImageFormat.YUV_420_888)
mInputAllocation = Allocation.createTyped(rs, yuvTypeBuilder.create(),
Allocation.USAGE_IO_INPUT or Allocation.USAGE_SCRIPT)
val rgbType = Type.createXY(rs, Element.RGBA_8888(rs), width, height)
mOutputAllocation = Allocation.createTyped(rs, rgbType,
Allocation.USAGE_IO_OUTPUT or Allocation.USAGE_SCRIPT)
}
fun setOutputSurface(output: Surface) {
mOutputAllocation!!.surface = output
}
override fun onBufferAvailable(a: Allocation) {
// Get the new frame into the input allocation
val startTime = System.currentTimeMillis()
a.ioReceive()
mScriptC.setInput(a)
mScriptC.forEach(mOutputAllocation)
mOutputAllocation!!.ioSend()
val endTime1 = System.currentTimeMillis()
Log.d(TAG, """processImage: put memory: ${endTime1 - startTime}ms""")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment