android - 直接在android中裁剪YUV420/NV21字节数组

标签 android crop libyuv

我需要从相机的 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);

}

最佳答案

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结构:
enter image description here
P.S.:另外,如果你的矩形的起始位置是奇数,U 和 V 将被交换。为了处理这种情况,我使用:
    if (cropRect.left % 2 == 1) {
        cropRect.left -= 1;
    }
    if (cropRect.top % 2 == 1) {
        cropRect.top -= 1;
    }

关于android - 直接在android中裁剪YUV420/NV21字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36918352/

相关文章:

c - 如何通过 libyuv::I420Scale 为 android 前置摄像头实现 Mirror?

c# - NV12格式和UV平面

android - 如何使用 Drawable 从 drawable 文件夹中获取所有图像作为位图数组?

带有图标的 Android 滑动 TabLayout

android - 即使按照实际程序也无法解析android中的json数据

java - 在适配器内打开一个对话框返回空值

android - 在android中选择并裁剪最大尺寸

node.js - Node gm - 使用裁剪和调整大小会导致错误

java - Java中按多边形区域裁剪图像

audio - .yuv测试视频序列的音频源是否可用?