title: OpenCV Java RGB BGR
body: <p>I tried several times to obtain a normal video in Java with OpenCV but all the time I have the colours switched: I mean when I run the program blue is orange in the video.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class Mat2Image {
  
      BufferedImage img;
      Mat mat = new Mat();
      byte[] dat;
      int elemSize;
      public Mat2Image() {
      }
      public Mat2Image(Mat mat) {
          getSpace(mat);
      }
      public void getSpace(Mat mat) {
          this.mat = mat;
          elemSize=(int)mat.elemSize();
          int w = mat.cols(), h = mat.rows();
          if (dat == null || dat.length != w * h * elemSize)
              dat = new byte[w * h * elemSize];
  
                if (img == null || img.getWidth() != w || img.getHeight() != h
              || img.getType() != BufferedImage.TYPE_3BYTE_BGR)
             img = new BufferedImage(w, h,BufferedImage.TYPE_3BYTE_BGR);
  
          }
          BufferedImage getImage(Mat mat){
              getSpace(mat);
  //        byte b;
  //        for(int i=0;i&lt;dat.length;i=i+3){
  //           b=dat[i];
  //           dat[i]=dat[i+2];
  //           dat[i+2]=b;
  //        }
              mat.get(0, 0, dat);
              img.getRaster().setDataElements(0, 0, 
                                 mat.cols(), mat.rows(), dat);
          return img;
      }
      static{
          System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  
      }
  
  }
  </code></pre>