在 Android 的 onPreviewFrame 期间转换 YUV->RGB(图像处理)->YUV?

新手上路,请多包涵

我正在使用 SurfaceView 捕获图像并在 public void onPreviewFrame4(byte[] data, Camera camera) 中获取 Yuv Raw 预览数据

我必须在 onPreviewFrame 中执行一些图像预处理,所以我需要将 Yuv 预览数据转换为 RGB 数据,而不是图像预处理并返回 Yuv 数据。

我已经使用这两个函数将 Yuv 数据编码和解码为 RGB,如下所示:

 public void onPreviewFrame(byte[] data, Camera camera) {
    Point cameraResolution = configManager.getCameraResolution();
    if (data != null) {
        Log.i("DEBUG", "data Not Null");

                // Preprocessing
                Log.i("DEBUG", "Try For Image Processing");
                Camera.Parameters mParameters = camera.getParameters();
                Size mSize = mParameters.getPreviewSize();
                int mWidth = mSize.width;
                int mHeight = mSize.height;
                int[] mIntArray = new int[mWidth * mHeight];

                // Decode Yuv data to integer array
                decodeYUV420SP(mIntArray, data, mWidth, mHeight);

                // Converting int mIntArray to Bitmap and
                // than image preprocessing
                // and back to mIntArray.

                // Encode intArray to Yuv data
                encodeYUV420SP(data, mIntArray, mWidth, mHeight);
                    }
}

    static public void decodeYUV420SP(int[] rgba, byte[] yuv420sp, int width,
        int height) {
    final int frameSize = width * height;

    for (int j = 0, yp = 0; j < height; j++) {
        int uvp = frameSize + (j >> 1) * width, u = 0, v = 0;
        for (int i = 0; i < width; i++, yp++) {
            int y = (0xff & ((int) yuv420sp[yp])) - 16;
            if (y < 0)
                y = 0;
            if ((i & 1) == 0) {
                v = (0xff & yuv420sp[uvp++]) - 128;
                u = (0xff & yuv420sp[uvp++]) - 128;
            }

            int y1192 = 1192 * y;
            int r = (y1192 + 1634 * v);
            int g = (y1192 - 833 * v - 400 * u);
            int b = (y1192 + 2066 * u);

            if (r < 0)
                r = 0;
            else if (r > 262143)
                r = 262143;
            if (g < 0)
                g = 0;
            else if (g > 262143)
                g = 262143;
            if (b < 0)
                b = 0;
            else if (b > 262143)
                b = 262143;

            // rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) &
            // 0xff00) | ((b >> 10) & 0xff);
            // rgba, divide 2^10 ( >> 10)
            rgba[yp] = ((r << 14) & 0xff000000) | ((g << 6) & 0xff0000)
                    | ((b >> 2) | 0xff00);
        }
    }
}

    static public void encodeYUV420SP_original(byte[] yuv420sp, int[] rgba,
        int width, int height) {
    final int frameSize = width * height;

    int[] U, V;
    U = new int[frameSize];
    V = new int[frameSize];

    final int uvwidth = width / 2;

    int r, g, b, y, u, v;
    for (int j = 0; j < height; j++) {
        int index = width * j;
        for (int i = 0; i < width; i++) {
            r = (rgba[index] & 0xff000000) >> 24;
            g = (rgba[index] & 0xff0000) >> 16;
            b = (rgba[index] & 0xff00) >> 8;

            // rgb to yuv
            y = (66 * r + 129 * g + 25 * b + 128) >> 8 + 16;
            u = (-38 * r - 74 * g + 112 * b + 128) >> 8 + 128;
            v = (112 * r - 94 * g - 18 * b + 128) >> 8 + 128;

            // clip y
            yuv420sp[index++] = (byte) ((y < 0) ? 0 : ((y > 255) ? 255 : y));
            U[index] = u;
            V[index++] = v;
        }
    }

问题是编码和解码 Yuv 数据可能有一些错误,因为如果我跳过预处理步骤,那么编码的 Yuv 数据也不同于 PreviewCallback 的原始数据。

请帮我解决这个问题。我必须在 OCR 扫描中使用这段代码,所以我需要实现这种类型的逻辑。

如果有任何其他方式做同样的事情,请提供给我。

提前致谢。 :)

原文由 Hitesh Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

尽管文档建议您可以设置图像数据应以哪种格式从相机到达,但实际上您通常可以选择一种格式:NV21,一种 YUV 格式。有关此格式的大量信息,请参阅 http://www.fourcc.org/yuv.php#NV21 ,有关将其转换为 RGB 的理论信息,请参阅 http://www.fourcc.org/fccyvrgb.php 。在 Extract black and white image from android camera’s NV21 format 中有基于图片的解释。维基百科页面上有一个关于该主题的 android 特定部分(感谢@AlexCohn): YUV#Y’UV420sp (NV21) to RGB conversion (Android)

但是,一旦您设置了 onPreviewFrame 例程,从它发送给您的字节数组到有用数据的机制就有点不清楚了。从 API 8 开始,可以使用以下解决方案来获取包含图像 JPEG 的字节流(compressToJpeg 是 YuvImage 提供的唯一转换选项):

 // pWidth and pHeight define the size of the preview Frame
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Alter the second parameter of this to the actual format you are receiving
YuvImage yuv = new YuvImage(data, ImageFormat.NV21, pWidth, pHeight, null);

// bWidth and bHeight define the size of the bitmap you wish the fill with the preview image
yuv.compressToJpeg(new Rect(0, 0, bWidth, bHeight), 50, out);

然后可能需要将此 JPEG 转换为您想要的格式。如果你想要一个位图:

 byte[] bytes = out.toByteArray();
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

如果出于某种原因您无法执行此操作,则可以手动进行转换。这样做需要克服的一些问题:

  1. 数据以字节数组的形式到达。根据定义,字节是有符号数,这意味着它们从 -128 到 127。但是,数据实际上是无符号字节(0 到 255)。如果不解决这个问题,结果注定会有一些奇怪的剪辑效果。

  2. 数据的顺序非常特定(根据前面提到的网页),每个像素都需要仔细提取。

  3. 例如,每个像素都需要放在位图上的正确位置。这还需要一种相当混乱(在我看来)的方法来构建数据缓冲区,然后从中填充位图。

  4. 原则上,这些值应该存储 [16..240],但在发送到 onPreviewFrame 的数据中似乎存储了 [0..255]

  5. 几乎每个关于此事的网页都提出了不同的系数,甚至允许 [16..240] 与 [0..255] 选项。

  6. 如果你真的有 NV12(YUV420 的另一个变体),那么你将需要交换 U 和 V 的读取。

我提出了一个解决方案(似乎有效),要求更正、改进以及降低整个运行成本的方法。我设置它是为了希望弄清楚发生了什么,而不是为了速度而优化它。它创建一个预览图像大小的位图:

数据变量来自对 onPreviewFrame 的调用

// Define whether expecting [16..240] or [0..255]
boolean dataIs16To240 = false;

// the bitmap we want to fill with the image
Bitmap bitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
int numPixels = imageWidth*imageHeight;

// the buffer we fill up which we then fill the bitmap with
IntBuffer intBuffer = IntBuffer.allocate(imageWidth*imageHeight);
// If you're reusing a buffer, next line imperative to refill from the start,
// if not good practice
intBuffer.position(0);

// Set the alpha for the image: 0 is transparent, 255 fully opaque
final byte alpha = (byte) 255;

// Holding variables for the loop calculation
int R = 0;
int G = 0;
int B = 0;

// Get each pixel, one at a time
for (int y = 0; y < imageHeight; y++) {
    for (int x = 0; x < imageWidth; x++) {
        // Get the Y value, stored in the first block of data
        // The logical "AND 0xff" is needed to deal with the signed issue
        float Y = (float) (data[y*imageWidth + x] & 0xff);

        // Get U and V values, stored after Y values, one per 2x2 block
        // of pixels, interleaved. Prepare them as floats with correct range
        // ready for calculation later.
        int xby2 = x/2;
        int yby2 = y/2;

        // make this V for NV12/420SP
        float U = (float)(data[numPixels + 2*xby2 + yby2*imageWidth] & 0xff) - 128.0f;

        // make this U for NV12/420SP
        float V = (float)(data[numPixels + 2*xby2 + 1 + yby2*imageWidth] & 0xff) - 128.0f;

        if (dataIs16To240) {
            // Correct Y to allow for the fact that it is [16..235] and not [0..255]
            Y = 1.164*(Y - 16.0);

            // Do the YUV -> RGB conversion
            // These seem to work, but other variations are quoted
            // out there.
            R = (int)(Yf + 1.596f*V);
            G = (int)(Yf - 0.813f*V - 0.391f*U);
            B = (int)(Yf            + 2.018f*U);
        }
        else {
            // No need to correct Y
            // These are the coefficients proposed by @AlexCohn
            // for [0..255], as per the wikipedia page referenced
            // above
            R = (int)(Yf + 1.370705f*V);
            G = (int)(Yf - 0.698001f*V - 0.337633f*U);
            B = (int)(Yf               + 1.732446f*U);
        }

        // Clip rgb values to 0-255
        R = R < 0 ? 0 : R > 255 ? 255 : R;
        G = G < 0 ? 0 : G > 255 ? 255 : G;
        B = B < 0 ? 0 : B > 255 ? 255 : B;

        // Put that pixel in the buffer
        intBuffer.put(alpha*16777216 + R*65536 + G*256 + B);
    }
}

// Get buffer ready to be read
intBuffer.flip();

// Push the pixel information from the buffer onto the bitmap.
bitmap.copyPixelsFromBuffer(intBuffer);

正如@Timmmm 在下面指出的那样,您可以通过将比例因子乘以 1000(即 1.164 变为 1164)然后将最终结果除以 1000 来进行 int 转换。

原文由 Neil Townsend 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题