Skip to content

Commit ce90a2a

Browse files
committed
Use ByteBuffer to convert 3 channel color OpenCV Mat to PImage pixels.
Assumes output PImage is ARGB format.
1 parent cdfd376 commit ce90a2a

1 file changed

Lines changed: 24 additions & 5 deletions

File tree

src/gab/opencv/OpenCV.java

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,6 +1070,29 @@ public int getSize(){
10701070
}
10711071

10721072

1073+
/**
1074+
* Convert a 3 channel OpenCV Mat object into
1075+
* pixels to be shoved into a 4 channel ARGB PImage's
1076+
* pixel array.
1077+
*
1078+
* @param m
1079+
* A Mat you want converted
1080+
*/
1081+
public int[] threeChanMatToARGBPixels(Mat m){
1082+
int pImageChannels = 4;
1083+
int numPixels = m.width()*m.height();
1084+
int[] intPixels = new int[numPixels];
1085+
Mat m2 = new Mat();
1086+
1087+
// Assumes output PImage is ARGB.
1088+
Imgproc.cvtColor(m, m2, Imgproc.COLOR_RGB2RGBA);
1089+
byte[] matPixels = new byte[numPixels*pImageChannels];
1090+
1091+
m2.get(0,0, matPixels);
1092+
ByteBuffer.wrap(matPixels).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(intPixels);
1093+
return intPixels;
1094+
}
1095+
10731096
/**
10741097
* Convert a single channel, gray OpenCV Mat object into
10751098
* pixels to be shoved into a 4 channel ARGB PImage's
@@ -1131,11 +1154,7 @@ public void toPImage(Mat m, PImage img){
11311154
img.loadPixels();
11321155

11331156
if(m.channels() == 3){
1134-
byte[] matPixels = new byte[width*height*3];
1135-
m.get(0,0, matPixels);
1136-
for(int i = 0; i < m.width()*m.height()*3; i+=3){
1137-
img.pixels[PApplet.floor(i/3)] = parent.color(matPixels[i+2]&0xFF, matPixels[i+1]&0xFF, matPixels[i]&0xFF);
1138-
}
1157+
img.pixels = threeChanMatToARGBPixels(m);
11391158
} else if(m.channels() == 1){
11401159
img.pixels = grayMatToARGBPixels(m);
11411160
} else if(m.channels() == 4){

0 commit comments

Comments
 (0)