在android的onPreviewFrame中转换YUV-> RGB(图像处理) - > YUV?

Hit*_*tel 33 ocr android image-processing yuv android-camera

我正在使用SurfaceView捕获图像并在public void onPreviewFrame4(byte []数据,相机相机)中获取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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

提前致谢.:)

Nei*_*end 40

虽然文档建议您可以设置图像数据应从相机到达的格式,但实际上您通常可以选择一种格式:NV21,YUV格式.有关此格式的大量信息,请参阅http://www.fourcc.org/yuv.php#NV21,有关将其转换为RGB的理论信息,请参阅http://www.fourcc.org/fccyvrgb.php.在Android相机的NV21格式的Extract黑白图像中有一个基于图片的解释.

另一种称为YUV420SP的格式也非常普遍.

但是,一旦你设置了onPreviewFrame例程,从它发送给你的有用数据的字节数组的机制有点,嗯,不清楚.从API 8开始,可以使用以下解决方案来获取保留图像JPEG的ByteStream(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);
Run Code Online (Sandbox Code Playgroud)

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

byte[] bytes = out.toByteArray();
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Run Code Online (Sandbox Code Playgroud)

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

  1. 数据以字节数组到达.根据定义,字节是带符号的数字,意味着它们从-128到127.但是,数据实际上是无符号字节(0到255).如果没有处理,结果注定会产生一些奇怪的剪辑效果.

  2. 数据的排序非常具体(根据前面提到的网页),需要仔细提取每个像素.

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

  4. 如果你实际上有NV12(或420SP),那么你需要交换U和V的读数.

我提出了一个解决方案(似乎有效),要求更正,改进和使整个事情运行成本更低的方法.它创建一个与预览图像大小相同的位图:

数据变量来自对onPreviewFrame的调用

// 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;

// 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
        int Y = 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;

        // Do the YUV -> RGB conversion
        float Yf = 1.164f*((float)Y) - 16.0f;
        int R = (int)(Yf + 1.596f*V);
        int G = (int)(Yf - 0.813f*V - 0.391f*U);
        int B = (int)(Yf            + 2.018f*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);
Run Code Online (Sandbox Code Playgroud)

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

  • 我是唯一一个认为转换为 JPEG 并返回位图有点奇怪的人吗? (2认同)

Reu*_*ton 17

为什么不指定相机预览应提供RGB图像?

Camera.Parameters.setPreviewFormat(ImageFormat.RGB_565) ;

  • 请注意,这不适用于所有设备.默认格式为YUV,不支持预览为RGB的设备仍将为您提供YUV格式的图像. (56认同)
  • YUV21和YUV12是所有摄像机支持的图像格式,用于使用其他格式检查,如果您的摄像机支持该功能(如果不是回调仍将提供YUV21格式的数据).mCamera = Camera.open(); Camera.Parameters params = mCamera.getParameters(); for(int i:params.getSupportedPreviewFormats()){Log.e(TAG,"支持的预览格式为="+ i);} (3认同)

mur*_*glu 7

您可以使用 RenderScript -> ScriptIntrinsicYuvToRGB

Kotlin 示例

val rs = RenderScript.create(CONTEXT_HERE)
val yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))

val yuvType = Type.Builder(rs, Element.U8(rs)).setX(byteArray.size)
val inData = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT)

val rgbaType = Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height)
val outData = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT)

inData.copyFrom(byteArray)

yuvToRgbIntrinsic.setInput(inData)
yuvToRgbIntrinsic.forEach(outData)

val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
outData.copyTo(bitmap)
Run Code Online (Sandbox Code Playgroud)


Jer*_*ski 5

经过对三星S4迷你快速代码的一些测试(比Neil的[浮动!]快120%,比原来的Hitesh快30%):

static public void decodeYUV420SP(int[] rgba, byte[] yuv420sp, int width,
                                  int height) {


    final int frameSize = width * height;
// define variables before loops (+ 20-30% faster algorithm o0`)
int r, g, b, y1192, y, i, uvp, u, v;
        for (int j = 0, yp = 0; j < height; j++) {
            uvp = frameSize + (j >> 1) * width;
            u = 0;
        v = 0;
        for (i = 0; i < width; i++, yp++) {
            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;
            }

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

// Java's functions are faster then 'IFs'
                    r = Math.max(0, Math.min(r, 262143));
                g = Math.max(0, Math.min(g, 262143));
                b = Math.max(0, Math.min(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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

速度与YuvImage.compressToJpeg()相当,ByteArrayOutputStream为输出(640x480图像为30-50 ms).

结果:三星S4 mini(2x1.7GHz)无法压缩为JPEG /实时将YUV转换为RGB(640x480 @ 30fps)


小智 5

Java 实现比 c 版本慢 10 倍,我建议您使用 GPUImage 库或仅移动这部分代码。

有一个 android 版本的 GPUImage:https : //github.com/Cyber​​Agent/android-gpuimage

如果你使用 gradle,你可以包含这个库,并调用方法: GPUImageNativeLibrary.YUVtoRBGA( inputArray, WIDTH, HEIGHT, outputArray);

我比较了时间,对于一个 960x540 的 NV21 图像,使用上面的 java 代码,它花费 200ms+,使用 GPUImage 版本,只有 10ms~20ms。


pro*_*ogm 1

您可以使用ColorHelper库来实现此目的:

using ColorHelper;

YUV yuv = new YUV(0.1, 0.1, 0.2);
RGB rgb = ColorConverter.YuvToRgb(yuv);
Run Code Online (Sandbox Code Playgroud)

链接: