JAVA语言,RGB格式顺时针旋转(90度,180度,270度) + 水平镜像旋转

前言

在图像处理领域,RGB格式是经常使用的一种格式,比如:Android应用中展示一张Bitmap、人工智能识别领域识别一张图片等等。
RGB格式指的是每个像素点是由RGB组成的,同时它的排列方式是R G B交替出现的:

  • RGBRGBRGB…

在图像处理的过程中,经常存在需要旋转图像的情况:

  • 顺时针旋转(摄像头角度的纠正等)
  • 水平镜像旋转(前置摄像头镜像照片的纠正等)

我们这里提供一些基础的代码,实现这样的目的:

  • 顺时针旋转 90度、180度、270度(rgbBytesRotateClockwise())
  • 水平镜像旋转(rgbBytesRotateMirror())

JAVA代码

public static final int TYPE_ROTATE_90 = 1;
public static final int TYPE_ROTATE_180 = 2;
public static final int TYPE_ROTATE_270 = 3;
public static byte[] rgbBytesRotateClockwise(byte[] rgbBytes, int width, int height, int rotateType) {
    byte[] _newRgbBytes = rgbBytes.clone();
    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {
            if (rotateType == TYPE_ROTATE_90) {
                _newRgbBytes[(i * height + (height - 1 - j)) * 3] = rgbBytes[(j * width + i) * 3];
                _newRgbBytes[(i * height + (height - 1 - j)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                _newRgbBytes[(i * height + (height - 1 - j)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
            } else if (rotateType == TYPE_ROTATE_180) {
                _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3] = rgbBytes[(j * width + i) * 3];
                _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                _newRgbBytes[((height - 1 - j) * width + (width - 1 - i)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
            } else {
                _newRgbBytes[((width - 1 - i) * height + j) * 3] = rgbBytes[(j * width + i) * 3];
                _newRgbBytes[((width - 1 - i) * height + j) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
                _newRgbBytes[((width - 1 - i) * height + j) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
            }
        }
    }

    return _newRgbBytes;
}

// 水平镜像
public static byte[] rgbBytesRotateMirror(byte[] rgbBytes, int width, int height) {
    byte[] _newRgbBytes = rgbBytes.clone();
    for (int j = 0; j < height; j++) {
        for (int i = 0; i < width; i++) {
            _newRgbBytes[(j * width + (width - 1 - i)) * 3] = rgbBytes[(j * width + i) * 3];
            _newRgbBytes[(j * width + (width - 1 - i)) * 3 + 1] = rgbBytes[(j * width + i) * 3 + 1];
            _newRgbBytes[(j * width + (width - 1 - i)) * 3 + 2] = rgbBytes[(j * width + i) * 3 + 2];
        }
    }

    return _newRgbBytes;
}

你可能感兴趣的:(Android开发,android,java,开发语言)