android camera yuv Frame Horizontal Flip Example

  • 2021-09-24 23:50:27
  • OfStack

When previewing Camera, it is necessary to flip the yuv frame horizontally, and call the Mirror function directly in onPreviewFrame (byte [] data, Camera camera). The processed picture has a horizontal flip relationship with the preview effect.

Mirroring algorithm for nv21:


  private void Mirror(byte[] src, int w, int h) { //src Is primitive yuv Array 
    int i;
    int index;
    byte temp;
    int a, b;
    //mirror y
    for (i = 0; i < h; i++) {
      a = i * w;
      b = (i + 1) * w - 1;
      while (a < b) {
        temp = src[a];
        src[a] = src[b];
        src[b] = temp;
        a++;
        b--;
      }
    }
 
    // mirror u and v
    index = w * h;
    for (i = 0; i < h / 2; i++) {
      a = i * w;
      b = (i + 1) * w - 2;
      while (a < b) {
        temp = src[a + index];
        src[a + index] = src[b + index];
        src[b + index] = temp;
 
        temp = src[a + index + 1];
        src[a + index + 1] = src[b + index + 1];
        src[b + index + 1] = temp;
        a+=2;
        b-=2;
      }
    }
  }

Mirroring algorithm for i420:


private void Mirror(byte[] src, int w, int h) { //src Is primitive yuv Array 
    int i;
    int index;
    byte temp;
    int a, b;
    //mirror y
    for (i = 0; i < h; i++) {
      a = i * w;
      b = (i + 1) * w - 1;
      while (a < b) {
        temp = src[a];
        src[a] = src[b];
        src[b] = temp;
        a++;
        b--;
      }
    }
    //mirror u
    index = w * h;//U Starting position 
    for (i = 0; i < h / 2; i++) {
      a = i * w / 2;
      b = (i + 1) * w / 2 - 1;
      while (a < b) {
        temp = src[a + index];
        src[a + index] = src[b + index];
        src[b + index] = temp;
        a++;
        b--;
      }
    }
    //mirror v
    index = w * h / 4 * 5;//V Starting position 
    for (i = 0; i < h / 2; i++) {
      a = i * w / 2;
      b = (i + 1) * w / 2 - 1;
      while (a < b) {
        temp = src[a + index];
        src[a + index] = src[b + index];
        src[b + index] = temp;
        a++;
        b--;
      }
    }

I420, YV12, NV12 and NV21 all belong to YUV420. The following is the arrangement order of the four formats:

I420: YYYYYYYY UUVV = > YUV420P
YV12: YYYYYYYY VVUU = > YUV420P
NV12: YYYYYYYY UVUV = > YUV420SP
NV21: YYYYYYYY VUVU = > YUV420SP


Related articles: