imageToTensor static method

Future<List<List<List<List<double>>>>> imageToTensor(
  1. Uint8List imageBytes,
  2. int tensorWidth,
  3. int tensorHeight
)

Converte bytes de imagem em um tensor 4D normalizado

Implementation

static Future<List<List<List<List<double>>>>> imageToTensor(
  Uint8List imageBytes,
  int tensorWidth,
  int tensorHeight,
) async {
  final originalImage = img.decodeImage(imageBytes);
  if (originalImage == null) {
    throw Exception('Erro ao decodificar imagem');
  }

  final resizedImage = img.copyResize(
    originalImage,
    width: tensorWidth,
    height: tensorHeight,
  );

  final tensor = List.generate(
    1,
    (_) => List.generate(
      tensorHeight,
      (_) => List.generate(tensorWidth, (_) => List.generate(3, (_) => 0.0)),
    ),
  );

  int pixelIndex = 0;
  for (final pixel in resizedImage) {
    final y = pixelIndex ~/ tensorWidth;
    final x = pixelIndex % tensorWidth;

    tensor[0][y][x][0] = pixel.r / pixel.maxChannelValue;
    tensor[0][y][x][1] = pixel.g / pixel.maxChannelValue;
    tensor[0][y][x][2] = pixel.b / pixel.maxChannelValue;

    pixelIndex++;
  }

  return tensor;
}