如何在Flutter中对相机图像进行正方形裁剪

3

我正在创建一个扫描器,需要为相机预览实现正方形叠加层。从相机预览获取图像流并将其发送到API后,我需要在将其发送到API之前对从相机预览中拍摄的 cameraImage 进行正方形裁剪。

我只有 cameraImage - 它是 YUV 420 格式 - 如何编程裁剪它?

1个回答

3
我猜你编写了类似以下代码来获取完整的图片:

```

Uint8List getBytes() {
    final WriteBuffer allBytes = WriteBuffer();
    for (final Plane plane in cameraImage.planes) {
        allBytes.putUint8List(plane.bytes);
    }
    return allBytes.done().buffer.asUint8List();
}

实际上,您是将YUV的三个平面的数据依次连接在一起:先是所有的Y,然后是所有的U,最后是所有的V。 正如您可以在维基百科页面上看到的那样,平面Y的宽度和高度与图像相同,而平面U和V使用宽度/2和高度/2。 如果我们按字节顺序进行,那么上述代码类似于以下代码:
int divider = 1; // for first plane: Y
for (final Plane plane in cameraImage.planes) {
    for (int i = 0; i < cameraImage.height ~/ divider; i++) {
        for (int j = 0; j < cameraImage.width ~/ divider; j++) {
            allBytes.putUint8(plane.bytes[j + i * cameraImage.width ~/ divider]);
        }
    }
    divider = 2; // for planes U and V
}

既然你在这里,我认为你已经知道如何裁剪了:

int divider = 1; // for first plane: Y
for (final Plane plane in cameraImage.planes) {
  for (int i = cropTop ~/ divider; i < cropBottom ~/ divider; i++) {
    for (int j = cropLeft ~/ divider; j < cropRight ~/ divider; j++) {
      allBytes.putUint8(plane.bytes[j + i * cameraImage.width ~/ divider]);
    }
  }
  divider = 2; // for planes U and V
}

在这里,裁剪*变量是从完整图像中计算出来的。

这是理论:这段代码没有考虑相机方向、奇数大小的可能副作用以及性能问题。但这是一个总体的想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接