1. 程式人生 > >android for opencv (2)byte[] ,Bitmap 與 Mat 型別轉換

android for opencv (2)byte[] ,Bitmap 與 Mat 型別轉換

(一) 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 

https://www.jb51.net/article/137657.htm

https://github.com/fiubaar/cliente/blob/3466e5e35a8459aef7174cf6b64a2ce81916656a/src/com/fi/uba/ar/utils/MatUtils.java