Created
August 14, 2023 13:40
-
-
Save Alexi-Zemcov/46236ae3c10165667ed2f78c6d89d7af to your computer and use it in GitHub Desktop.
prepareImage
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
/// Изменение размера, разворот изображения. | |
/// | |
/// Чтобы изображение не искажалось преобразование происходит | |
/// по высоте (или ширине, в зависимости от соотношения [image.width]/[image.height]). | |
/// | |
/// Дальнейшее выравнивание под размеры (заполнение матрицы) происходит | |
/// в методе _getEncodeInputTensor. | |
Image prepareImage( | |
Image image, { | |
required int targetHeight, | |
required int targetWidth, | |
}) { | |
final srcHeight = image.height; | |
final srcWidth = image.width; | |
if (srcHeight > srcWidth) { | |
final rotatedImage = copyRotate(image, angle: 270); | |
return prepareImage( | |
rotatedImage, | |
targetHeight: targetHeight, | |
targetWidth: targetWidth, | |
); | |
} | |
final srcRatio = srcWidth / srcHeight; | |
final targetRatio = targetWidth / targetHeight; | |
if (targetRatio > srcRatio) { | |
return copyResize( | |
image, | |
height: targetHeight, | |
width: (targetHeight * srcRatio).toInt(), | |
); | |
} | |
if (targetRatio < srcRatio) { | |
return copyResize( | |
image, | |
height: targetHeight, | |
width: (targetHeight * srcRatio).toInt(), | |
); | |
} | |
return copyResize( | |
image, | |
height: targetHeight, | |
width: targetWidth, | |
); | |
} | |
List<double> getEncodeInputNormalized({ | |
required Image image, | |
required int targetImageHeight, | |
required int targetImageWidth, | |
}) { | |
final input = | |
List<double>.filled(targetImageHeight * targetImageWidth, 0.0); | |
final imageWidth = image.width; | |
// Смещение offset нужно чтобы паддинг был симметрично по бокам, а не только справа. | |
final offset = ((targetImageWidth - imageWidth) / 2).round(); | |
for (var cHeight = 0; cHeight < targetImageHeight; ++cHeight) { | |
for (var cWidth = 0; cWidth < targetImageWidth; ++cWidth) { | |
if (cWidth < imageWidth && cHeight < image.height) { | |
input[cHeight * targetImageWidth + cWidth + offset] = | |
((image.getPixel(cWidth, cHeight).luminance / 255.0) - 0.5) / 0.5; | |
} | |
} | |
} | |
return input; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment