Last active
February 4, 2021 17:36
-
-
Save SilviaSantano/6b46b7cf47ddfc8a73227b68d246d5bf to your computer and use it in GitHub Desktop.
Get Correction Matrix for mapping coordinates between two different coordinate systems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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