web-dev-qa-db-ja.com

AndroidのonPreviewFrame中にYUV-> RGB(画像処理)-> YUVを変換しますか?

SurfaceViewを使用して画像をキャプチャし、Yuv Rawプレビューデータを取得しています public void onPreviewFrame4(byte [] data、Camera camera)

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データがPreviewCallbackの元のデータと異なるため、Yuvデータのエンコードとデコードに誤りがある可能性があることです。

この問題を解決するのを手伝ってください。 OCRスキャンでこのコードを使用する必要があるため、このタイプのロジックを実装する必要があります。

同じことをする他の方法があれば私に提供してください。

前もって感謝します。 :)

32
Hitesh Patel

カメラプレビューがRGB画像を提供するように指定しないのはなぜですか?

すなわち Camera.Parameters.setPreviewFormat(ImageFormat.RGB_565) ;

17
Reuben Scratton

ドキュメントでは、カメラから画像データを受信する形式を設定できることが示唆されていますが、実際には、YUV形式であるNV21のいずれかを選択することがよくあります。この形式に関する多くの情報については http://www.fourcc.org/yuv.php#NV21 を参照してください。RGBへの変換の背後にある理論については http:// www.fourcc.org/fccyvrgb.phpAndroidカメラのNV21形式 から白黒画像を抽出)に写真ベースの説明があります。

YUV420SPと呼ばれる別の形式も非常に普及しています。

ただし、onPreviewFrameルーチンを設定すると、それが送信するバイト配列から有用なデータに移動するメカニズムは、やや不明瞭です。 API 8以降、次のソリューションを使用して、画像のJPEGを保持するByteStreamを取得できます(YuvImageが提供する唯一の変換オプションはcompressToJpegです)。

// 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. データは非常に特定の順序で(前述のWebページによる)、各ピクセルを慎重に抽出する必要があります。

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

@Timmmmが以下で指摘しているように、スケーリング係数に1000を掛けて(つまり1.164が1164になる)intで変換し、最終結果を1000で除算することができます。

39
Neil Townsend

Samsung S4 miniの最速コードでいくつかのテストを行った後(Neilの[floats!]より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);
            }
        }
    }

速度はYuvImage.compressToJpeg()に相当し、出力としてByteArrayOutputStreamを使用します(640x480画像の場合は30-50ミリ秒)。

結果: Samsung S4 mini(2x1.7GHz)は、リアルタイムでJPEGに圧縮/ YUVをRGBに変換できません(640x480 @ 30fps)

5
JerzySkalski

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を使用します。

4
promenade

JellyBean 4.2(Api 17+)に付属のRenderScript ScriptIntrinsicYuvToRGBを試してください。

https://developer.Android.com/reference/Android/renderscript/ScriptIntrinsicYuvToRGB.html

Nexus 7(2013、JellyBean 4.3)では、1920x1080の画像変換(フルHDカメラプレビュー)には約7ミリ秒かかります。

1
Matti81

上記のコードスニペットを修正する

static public void decodeYUV420SP(int[] rgba, byte[] yuv420sp, int width,
                              int height) {
    final int frameSize = width * height;
    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) {
            // above answer is wrong at the following lines. just swap ***u*** and ***v*** 
                u = (0xff & yuv420sp[uvp++]) - 128;
                v = (0xff & yuv420sp[uvp++]) - 128;
            }

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

            r = Math.max(0, Math.min(r, 262143));
            g = Math.max(0, Math.min(g, 262143));
            b = Math.max(0, Math.min(b, 262143));

            // combine ARGB
            rgba[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00)
                    | ((b >> 10) | 0xff);
        }
    }
}
1
HC_ZZ

RenderScript-> ScriptIntrinsicYuvToRGBを使用できます

コトリンのサンプル

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)
1
murgupluoglu