nono
nono

Reputation: 1702

Flutter camera image conversion to image

I'm trying to convert a cameraImage using camera and image libraries.

I've tried many code snippet to do the conversion unsuccessfully.

Like this one: How to convert camera image to image?

Now, I'm trying to code my own conversion but it's still not working. (The size of the bytes[] is not matching because of some padding)

Here is the code of the conversion function.

imglib.Image convertCameraImage(CameraImage image) {
  int width = image.width;
  int height = image.height;
  Uint8List rgbData = Uint8List(width * height * 3);
  final int uvyButtonStride = image.planes[1].bytesPerRow;
  final int uvPixelStride = image.planes[1].bytesPerPixel!;

  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int uvIndex =
          uvPixelStride * (x / 2).floor() + uvyButtonStride * (y / 2).floor();

      final int index = y * width + x;
      final yp = image.planes[0].bytes[index];
      final up = image.planes[1].bytes[uvIndex];
      final vp = image.planes[2].bytes[uvIndex];

      // Calculate pixel color
      int r = (yp + 1.4075 * (vp - 128)).toInt().clamp(0, 255);
      int g = (yp - 0.3455 * (up - 128) - (0.7169 * (vp - 128)))
          .toInt()
          .clamp(0, 255);
      int b = (yp + 1.7790 * (up - 128)).toInt().clamp(0, 255);

      rgbData[index * 3] = r;
      rgbData[index * 3 + 1] = g;
      rgbData[index * 3 + 2] = b;
    }
  }

  var img = imglib.Image.fromBytes(
      width: width, height: height, bytes: rgbData.buffer);

  return img;
}

Upvotes: 1

Views: 30

Answers (0)

Related Questions