版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/piaoxuezhong/article/details/83832181
(一) byte[] 转换为Mat,Mat 转 byte[]
public Mat byteAndMat(Mat image) {
int width = image.cols();
int height = image.rows();
int dims = image.channels();
byte[] data = new byte[width*height*dims];
image.get(0, 0, data); //Mat转byte
int index = 0;
int r=0, g=0, b=0;
for(int row=0; row<height; row++) {
for(int col=0; col<width*dims; col+=dims) {
index = row*width*dims + col;
b = data[index]&0xff;
g = data[index+1]&0xff;
r = data[index+2]&0xff;
data[index] = (byte)b;
data[index+1] = (byte)g;
data[index+2] = (byte)r;
}
}
image.put(0, 0, data); //byte转Mat
return image;
}
(二)byte[] 转换为Bitmap ,Bitmap 转 byte[]
//Bitmap转byte
public static byte[] bitmapToByteArray(Bitmap image) {
//calculate how many bytes the image consists of.
int bytes = bm.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
image.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
return buffer.array(); //Get the underlying array containing the data.
}
//或者是下面的这种形式
public void BitmapToBYTE(Bitmap image) {
int bytes = image.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a buffer
image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer
byte[] temp = buffer.array(); // Get the underlying array
}
//Byte转Bitmap
public Bitmap ByteArray2Bitmap(byte[] data, int width, int height) {
int Size = width * height;
int[] rgba = new int[Size];
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++) {
rgba[i * width + j] = 0xff000000;
}
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bmp.setPixels(rgba, 0 , width, 0, 0, width, height);
return bmp;
}
(三)Mat与Bitmap类型转换
//Mat转Bitmap
public static Bitmap matToBitmap(Mat mat) {
Bitmap resultBitmap = null;
if (mat != null) {
resultBitmap = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
if (resultBitmap != null)
Utils.matToBitmap(mat, resultBitmap);
}
return resultBitmap;
}
//Bitmap转Mat
public static Mat bitmapToMat(Bitmap bm) {
Bitmap bmp32 = bm.copy(Bitmap.Config.RGB_565, true);
Mat imgMat = new Mat ( bm.getHeight(), bm.getWidth(), CvType.CV_8UC2, new Scalar(0));
Utils.bitmapToMat(bmp32, imgMat);
return imgMat;
}
参考:
https://blog.csdn.net/qluojieq/article/details/78289795?locationNum=7&fps=1
https://blog.csdn.net/u013547134/article/details/40918513