Android YUV图像转换算法和检测工具

1. 格式说明

在安卓开发的一些场景,比如操作相机输出、视频编解码中会用到YUV图像格式。YUV中最常用的是YUV420格式,YUV420就是每4个Y分量共用一个U分量和一个V分量。

YUV420分为4种:

  • I420: YYYYYYYY UU VV
  • YV12:YYYYYYYY VV UU
  • NV12:YYYYYYYY UVUV
  • NV21:YYYYYYYY VUVU

I420和YV12属于YUV420P,也就是U和V分开放置,不同的是I420是先放U,YV12是先放V;
NV12和NV21属于YUV420SP,也就是U和V交替放置,不同的是NV12是UV交替,NV21是VU交替。

这4种格式和名称是我总结了国内外很多篇资料得出来的,并且经过了算法检验,应该比较准确。国内部分资料可能有描述错误。

由于YUV420命名和格式有些乱(包括官方资料),对于新手来说,在做图像处理时,很容易弄错,导致输出的图像错乱。


device-2019-06-03-121131.png

我决定做一个能识别YUV420图像格式的工具。
当未知格式(是YUV420,但具体格式不确定)的图像数据输入时,它同时以I420、YV12、NV12和NV21这4种格式去解析图像,并实时显示。其中只有一种是显示正确的,另外三种都会有颜色异常。
此外再加上方向旋转(上图中的Rotate)和宽高交换(上图中的Flip)功能。

2. 数据来源

数据来源于安卓相机,分为Camera1和Camera2。Camera1是旧的API,标记为Deprecated,功能较简单,官方推荐用Camera2 API。Camera2功能更强大,使用起来也复杂一点。
它们的使用方法可参考官方Demo:

  1. Camera1官方Demo镜像
    https://github.com/appium/android-apidemos/blob/master/app/src/main/java/io/appium/android/apis/graphics/CameraPreview.java
  2. Camera2官方Demo
    https://github.com/googlesamples/android-Camera2Basic

Camera1获取输出的图像数据方法如下:


        // 1. 创建Camera.Parameters并设置预览图像格式
       Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        parameters.setPreviewFormat(ImageFormat.YV12); 
        requestLayout();
        mCamera.setParameters(parameters);

        // 2. 设置预览图像回调
        mCamera = Camera.open();
        mCamera.setPreviewCallback(this);

        // 3. 处理回调图像的byte[]数据
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        ...
    }

Camera2获取输出的图像数据方法如下:

        // 1. 创建ImageReader并设置图像格式
                mImageReader = ImageReader.newInstance(640, 480,
                        ImageFormat.YUV_420_888, /*maxImages*/2);
                mImageReader.setOnImageAvailableListener(
                        mOnImageAvailableListener, mBackgroundHandler);

        // 2. 从ImageReader中取得getSurface()并传给mCameraDevice
            mPreviewRequestBuilder.addTarget(mImageReader.getSurface());

            // Here, we create a CameraCaptureSession for camera preview.
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

        // 3. 在ImageReader的OnImageAvailableListener回调中获取Image数据
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            handleImage(reader);
        }

    };

3. 格式转换算法

为了简单起见,我的工具中使用4个ImageView来展示图像。不用担心图像是静止的,由于不停刷新,图像是实时运动的。原始图像需要转成Bitmap才能在ImageView中显示。

YUV420转Bitmap算法:

    public static Bitmap nv12ToBitmap(byte[] data, int w, int h) {
        return spToBitmap(data, w, h, 0, 1);
    }

    public static Bitmap nv21ToBitmap(byte[] data, int w, int h) {
        return spToBitmap(data, w, h, 1, 0);
    }

    private static Bitmap spToBitmap(byte[] data, int w, int h, int uOff, int vOff) {
        int plane = w * h;
        int[] colors = new int[plane];
        int yPos = 0, uvPos = plane;
        for(int j = 0; j < h; j++) {
            for(int i = 0; i < w; i++) {
                // YUV byte to RGB int
                final int y1 = data[yPos] & 0xff;
                final int u = (data[uvPos + uOff] & 0xff) - 128;
                final int v = (data[uvPos + vOff] & 0xff) - 128;
                final int y1192 = 1192 * y1;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                r = (r < 0) ? 0 : ((r > 262143) ? 262143 : r);
                g = (g < 0) ? 0 : ((g > 262143) ? 262143 : g);
                b = (b < 0) ? 0 : ((b > 262143) ? 262143 : b);
                colors[yPos] = ((r << 6) & 0xff0000) |
                        ((g >> 2) & 0xff00) |
                        ((b >> 10) & 0xff);

                if((yPos++ & 1) == 1) uvPos += 2;
            }
            if((j & 1) == 0) uvPos -= w;
        }
        return Bitmap.createBitmap(colors, w, h, Bitmap.Config.RGB_565);
    }

    public static Bitmap i420ToBitmap(byte[] data, int w, int h) {
        return pToBitmap(data, w, h, true);
    }

    public static Bitmap yv12ToBitmap(byte[] data, int w, int h) {
        return pToBitmap(data, w, h, false);
    }

    private static Bitmap pToBitmap(byte[] data, int w, int h, boolean uv) {
        int plane = w * h;
        int[] colors = new int[plane];
        int off = plane >> 2;
        int yPos = 0, uPos = plane + (uv ? 0 : off), vPos = plane + (uv ? off : 0);
        for(int j = 0; j < h; j++) {
            for(int i = 0; i < w; i++) {
                // YUV byte to RGB int
                final int y1 = data[yPos] & 0xff;
                final int u = (data[uPos] & 0xff) - 128;
                final int v = (data[vPos] & 0xff) - 128;
                final int y1192 = 1192 * y1;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                r = (r < 0) ? 0 : ((r > 262143) ? 262143 : r);
                g = (g < 0) ? 0 : ((g > 262143) ? 262143 : g);
                b = (b < 0) ? 0 : ((b > 262143) ? 262143 : b);
                colors[yPos] = ((r << 6) & 0xff0000) |
                        ((g >> 2) & 0xff00) |
                        ((b >> 10) & 0xff);

                if((yPos++ & 1) == 1) {
                    uPos++;
                    vPos++;
                }
            }
            if((j & 1) == 0) {
                uPos -= (w >> 1);
                vPos -= (w >> 1);
            }
        }
        return Bitmap.createBitmap(colors, w, h, Bitmap.Config.RGB_565);
    }

这是第一种方法,是Intel提供的。https://software.intel.com/en-us/android/articles/trusted-tools-in-the-new-android-world-optimization-techniques-from-intel-sse-intrinsics-to

另一种YUV420转Bitmap算法:

    public static Bitmap nv21ToBitmap(byte[] data, int w, int h) {
        final YuvImage image = new YuvImage(data, ImageFormat.NV21, w, h, null);
        ByteArrayOutputStream os = new ByteArrayOutputStream(data.length);
        if (image.compressToJpeg(new Rect(0, 0, w, h), 100, os)) {
            byte[] tmp = os.toByteArray();
            return BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
        }
        return null;
    }

这种方法是利用安卓提供的YuvImage类将NV21格式转换成Bitmap。虽然这是官方的,但是转换效率比较低,比第一种方法慢一倍,而且只支持NV21格式,所以不推荐使用。

Camera2的图像数据回调中提供的是ImageReader,需要从ImageReader中获取Image.Plane[],再转换成byte[]数据。方法如下:

    /**
     * 从ImageReader中获取byte[]数据
     */
    public static byte[] getBytesFromImageReader(ImageReader imageReader) {
        try (Image image = imageReader.acquireNextImage()) {
            final Image.Plane[] planes = image.getPlanes();
            int len = 0;
            for (Image.Plane plane : planes) {
                len += plane.getBuffer().remaining();
            }
            byte[] bytes = new byte[len];
            int off = 0;
            for (Image.Plane plane : planes) {
                ByteBuffer buffer = plane.getBuffer();
                int remain = buffer.remaining();
                buffer.get(bytes, off, remain);
                off += remain;
            }
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

4. 旋转算法


    // NV21或NV12顺时针旋转90度
    public static void rotateSP90(byte[] src, byte[] dest, int w, int h) {
        int pos = 0;
        int k = 0;
        for (int i = 0; i <= w - 1; i++) {
            for (int j = h - 1; j >= 0; j--) {
                dest[k++] = src[j * w + i];
            }
        }

        pos = w * h;
        for (int i = 0; i <= w - 2; i += 2) {
            for (int j = h / 2 - 1; j >= 0; j--) {
                dest[k++] = src[pos + j * w + i];
                dest[k++] = src[pos + j * w + i + 1];
            }
        }
    }

    // NV21或NV12顺时针旋转270度
    public static void rotateSP270(byte[] src, byte[] dest, int w, int h) {
        int pos = 0;
        int k = 0;
        for (int i = w - 1; i >= 0; i--) {
            for (int j = 0; j <= h - 1; j++) {
                dest[k++] = src[j * w + i];
            }
        }

        pos = w * h;
        for (int i = w - 2; i >= 0; i -= 2) {
            for (int j = 0; j <= h / 2 - 1; j++) {
                dest[k++] = src[pos + j * w + i];
                dest[k++] = src[pos + j * w + i + 1];
            }
        }
    }

    // NV21或NV12顺时针旋转180度
    public static void rotateSP180(byte[] src, byte[] dest, int w, int h) {
        int pos = 0;
        int k = w * h - 1;
        while (k >= 0) {
            dest[pos++] = src[k--];
        }

        k = src.length - 2;
        while (pos < dest.length) {
            dest[pos++] = src[k];
            dest[pos++] = src[k + 1];
            k -= 2;
        }
    }

    // I420或YV12顺时针旋转90度
    public static void rotateP90(byte[] src, byte[] dest, int w, int h) {
        int pos = 0;
        //旋转Y
        int k = 0;
        for (int i = 0; i < w; i++) {
            for (int j = h - 1; j >= 0; j--) {
                dest[k++] = src[j * w + i];
            }
        }
        //旋转U
        pos = w * h;
        for (int i = 0; i < w / 2; i++) {
            for (int j = h / 2 - 1; j >= 0; j--) {
                dest[k++] = src[pos + j * w / 2 + i];
            }
        }

        //旋转V
        pos = w * h * 5 / 4;
        for (int i = 0; i < w / 2; i++) {
            for (int j = h / 2 - 1; j >= 0; j--) {
                dest[k++] = src[pos + j * w / 2 + i];
            }
        }
    }

    // I420或YV12顺时针旋转270度
    public static void rotateP270(byte[] src, byte[] dest, int w, int h) {
        int pos = 0;
        //旋转Y
        int k = 0;
        for (int i = w - 1; i >= 0; i--) {
            for (int j = 0; j < h; j++) {
                dest[k++] = src[j * w + i];
            }
        }
        //旋转U
        pos = w * h;
        for (int i = w / 2 - 1; i >= 0; i--) {
            for (int j = 0; j < h / 2; j++) {
                dest[k++] = src[pos + j * w / 2 + i];
            }
        }

        //旋转V
        pos = w * h * 5 / 4;
        for (int i = w / 2 - 1; i >= 0; i--) {
            for (int j = 0; j < h / 2; j++) {
                dest[k++] = src[pos + j * w / 2 + i];
            }
        }
    }

    // I420或YV12顺时针旋转180度
    public static void rotateP180(byte[] src, byte[] dest, int w, int h) {
        int pos = 0;
        int k = w * h - 1;
        while (k >= 0) {
            dest[pos++] = src[k--];
        }

        k = w * h * 5 / 4;
        while (k >= w * h) {
            dest[pos++] = src[k--];
        }

        k = src.length - 1;
        while (pos < dest.length) {
            dest[pos++] = src[k--];
        }
    }

注意,如果旋转角度是90或270度,那么旋转后图像宽高就交换了。

5. 检测工具

有了数据来源和算法,封装一个检测工具用来展示就简单了。检测工具YUVDetectView继承自FrameLayout,里面放4个ImageView。

public class YUVDetectView extends FrameLayout {

    ImageView[] ivs;
    CheckBox cb;
    boolean isFlip = false;
    boolean isShowing = false;
    int rotation = 0;

    public YUVDetectView(@NonNull Context context) {
        this(context, null);
    }

    public YUVDetectView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public YUVDetectView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflate(context, R.layout.view_yuv_detect, this);

        ivs = new ImageView[]{
                findViewById(R.id.iv1), // I420
                findViewById(R.id.iv2), // YV12
                findViewById(R.id.iv3), // NV12
                findViewById(R.id.iv4), // NV21
        };
        cb = findViewById(R.id.cb);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isFlip = isChecked;
            }
        });

        View btn = findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rotation = (rotation + 90) % 360;
            }
        });
    }

    public void input(final ImageReader imageReader) {
        final int w = isFlip ? imageReader.getHeight() : imageReader.getWidth();
        final int h = isFlip ? imageReader.getWidth() : imageReader.getHeight();
        final byte[] bytes = YUVTools.getBytesFromImageReader(imageReader);
        if(bytes != null) {
            displayImage(bytes, w, h);
        }
    }

    public void inputAsync(final byte[] data, int width, int height) {
        final int w = isFlip ? height : width;
        final int h = isFlip ? width : height;

        if (isShowing) return;
        isShowing = true;
        new Thread() {
            @Override
            public void run() {
                displayImage(data, w, h);
                isShowing = false;
            }
        }.start();
    }

    private void displayImage(byte[] data, int w, int h) {
        long time = System.currentTimeMillis();

        byte[] rotated = rotation == 0 ? data : new byte[data.length];
        int rw = rotation % 180 == 0 ? w : h, rh = rotation % 180 == 0 ? h : w; // rotated

        YUVTools.rotateP(data, rotated, w, h, rotation);
        final Bitmap b0 = YUVTools.i420ToBitmap(rotated, rw, rh);

        YUVTools.rotateP(data, rotated, w, h, rotation);
        final Bitmap b1 = YUVTools.yv12ToBitmap(rotated, rw, rh);

        YUVTools.rotateSP(data, rotated, w, h, rotation);
        final Bitmap b2 = YUVTools.nv12ToBitmap(rotated, rw, rh);

        YUVTools.rotateSP(data, rotated, w, h, rotation);
        final Bitmap b3 = YUVTools.nv21ToBitmap(rotated, rw, rh);

        time = System.currentTimeMillis() - time;
        Log.d("YUVDetectView", "convert time: " + time);
        post(new Runnable() {
            @Override
            public void run() {
                if (b0 != null) ivs[0].setImageBitmap(b0);
                if (b1 != null) ivs[1].setImageBitmap(b1);
                if (b2 != null) ivs[2].setImageBitmap(b2);
                if (b3 != null) ivs[3].setImageBitmap(b3);
            }
        });
    }d
}

Github地址

https://github.com/rome753/android-YuvTools

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容