Skip to content

Instantly share code, notes, and snippets.

@SilviaSantano
Last active February 4, 2021 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SilviaSantano/6b46b7cf47ddfc8a73227b68d246d5bf to your computer and use it in GitHub Desktop.
Save SilviaSantano/6b46b7cf47ddfc8a73227b68d246d5bf to your computer and use it in GitHub Desktop.
Get Correction Matrix for mapping coordinates between two different coordinate systems
/**
* Compute a matrix to transform the coordinates of an object in the image from image analysis to the preview.
*/
fun computeImageToPreviewConversionMatrix(previewView: PreviewView, image: ImageProxy): Matrix {
val cropRect = image.cropRect
val rotationDegrees = image.imageInfo.rotationDegrees
val matrix = Matrix()
// A float array of the source vertices (crop rect) in clockwise order.
val source = floatArrayOf(
cropRect.left.toFloat(),
cropRect.top.toFloat(),
cropRect.right.toFloat(),
cropRect.top.toFloat(),
cropRect.right.toFloat(),
cropRect.bottom.toFloat(),
cropRect.left.toFloat(),
cropRect.bottom.toFloat()
)
// A float array of the destination vertices in clockwise order.
val destination = floatArrayOf(
0f,
0f,
previewView.width.toFloat(),
0f,
previewView.width.toFloat(),
previewView.height.toFloat(),
0f,
previewView.height.toFloat()
)
// The destination vertexes need to be shifted based on rotation degrees. The
// rotation degree represents the clockwise rotation needed to correct the image.
// Each vertex is represented by 2 float numbers in the vertices array.
val vertexSize = 2
// The destination needs to be shifted 1 vertex for every 90° rotation.
val shiftOffset = rotationDegrees / 90 * vertexSize;
val tempArray = destination.clone()
for (toIndex in source.indices) {
val fromIndex = (toIndex + shiftOffset) % source.size
destination[toIndex] = tempArray[fromIndex]
}
matrix.setPolyToPoly(source, 0, destination, 0, 4)
return matrix
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment