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;
}
@Spaxe
Copy link
Author

Spaxe commented Sep 18, 2014

For error

A library relies on native code that's not available.
Or only works properly when the sketch is run as a 32-bit  application

Make sure your main program (such as in void setup()) loads the native OpenCV library:

import org.opencv.core.Core;
...
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

@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