Skip to content

Instantly share code, notes, and snippets.

@Spaxe
Created September 18, 2014 06:32
Show Gist options
  • Save Spaxe/3543f0005e9f8f3c4dc5 to your computer and use it in GitHub Desktop.
Save Spaxe/3543f0005e9f8f3c4dc5 to your computer and use it in GitHub Desktop.
OpenCV cv::Mat <==> Processing PImage Converter Functions
import java.nio.*;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
// Convert PImage (ARGB) to Mat (CvType = CV_8UC4)
Mat toMat(PImage image) {
int w = image.width;
int h = image.height;
Mat mat = new Mat(h, w, CvType.CV_8UC4);
byte[] data8 = new byte[w*h*4];
int[] data32 = new int[w*h];
arrayCopy(image.pixels, data32);
ByteBuffer bBuf = ByteBuffer.allocate(w*h*4);
IntBuffer iBuf = bBuf.asIntBuffer();
iBuf.put(data32);
bBuf.get(data8);
mat.put(0, 0, data8);
return mat;
}
// Convert Mat (CvType=CV_8UC4) to PImage (ARGB)
PImage toPImage(Mat mat) {
int w = mat.width();
int h = mat.height();
PImage image = createImage(w, h, ARGB);
byte[] data8 = new byte[w*h*4];
int[] data32 = new int[w*h];
mat.get(0, 0, data8);
ByteBuffer.wrap(data8).asIntBuffer().get(data32);
arrayCopy(data32, image.pixels);
return image;
}
@collinalexbell
Copy link

Any idea why my image looks like this?

@collinalexbell
Copy link

Mat m2 = new Mat();
Imgproc.cvtColor(m, m2, Imgproc.COLOR_RGB2RGBA);

Fixed the issue for me. My cam is 3 chan, not 4 chan.

Source: https://github.com/atduskgreg/opencv-processing/blob/master/src/gab/opencv/OpenCV.java#L1210

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment