编程语言
首页 > 编程语言> > Android-YUV图像转换算法和检测工具

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

作者:互联网

1. 格式说明

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

YUV420分为4种:

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

标签:int,public,pos,YUV,++,Android,data,byte,检测工具
来源: https://www.cnblogs.com/rome753/p/16491470.html