Created
September 18, 2014 06:32
-
-
Save Spaxe/3543f0005e9f8f3c4dc5 to your computer and use it in GitHub Desktop.
OpenCV cv::Mat <==> Processing PImage Converter Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Any idea why my image looks like this?
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
For error
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);