【问题标题】:Crop YUV420/NV21 byte array directly in android直接在android中裁剪YUV420/NV21字节数组
【发布时间】:2016-08-23 10:26:43
【问题描述】:

我需要从相机的 onPreviewFrame 裁剪每一帧。我想直接裁剪它对字节数组进行操作而不将其转换为位图。我想直接在阵列上做的原因是它不能太慢或太贵。裁剪后直接使用输出字节数组,不需要任何位图转换。

int frameWidth;
int frameHeight;    

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
    // Crop the data array directly.

    cropData(data, frameWidth, frameHeight, startCropX, startCropY, outputWidth, outputHeight);

}

【问题讨论】:

  • 您是在寻求有关您编写的代码的帮助,还是要求某人为您编写代码?如果是前者,请展示您尝试过的内容并解释无效的内容。如果是后者,你可能来错地方了。

标签: android crop libyuv


【解决方案1】:
private static byte[] cropNV21(byte[] img, int imgWidth, @NonNull Rect cropRect) {
    // 1.5 mean 1.0 for Y and 0.25 each for U and V
    int croppedImgSize = (int)Math.floor(cropRect.width() * cropRect.height() * 1.5);
    byte[] croppedImg = new byte[croppedImgSize];

    // Start points of UV plane
    int imgYPlaneSize = (int)Math.ceil(img.length / 1.5);
    int croppedImgYPlaneSize = cropRect.width() * cropRect.height();

    // Y plane copy
    for (int w = 0; w < cropRect.height(); w++) {
        int imgPos = (cropRect.top + w) * imgWidth + cropRect.left;
        int croppedImgPos = w * cropRect.width();
        System.arraycopy(img, imgPos, croppedImg, croppedImgPos, cropRect.width());
    }

    // UV plane copy
    // U and V are reduced by 2 * 2, so each row is the same size as Y
    // and is half U and half V data, and there are Y_rows/2 of UV_rows
    for (int w = 0; w < (int)Math.floor(cropRect.height() / 2.0); w++) {
        int imgPos = imgYPlaneSize + (cropRect.top / 2 + w) * imgWidth + cropRect.left;
        int croppedImgPos = croppedImgYPlaneSize + (w * cropRect.width());
        System.arraycopy(img, imgPos, croppedImg, croppedImgPos, cropRect.width());
    }

    return croppedImg;
}

NV21 结构:

P.S.:另外,如果你的矩形的起始位置是奇数,U 和 V 将被交换。为了处理这种情况,我使用:

    if (cropRect.left % 2 == 1) {
        cropRect.left -= 1;
    }
    if (cropRect.top % 2 == 1) {
        cropRect.top -= 1;
    }

【讨论】:

  • 这对我很有效。我在 StackOverflow 上评估的几个最佳解决方案。谢谢!
猜你喜欢
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-02
相关资源
最近更新 更多