OpenCV and Processing 7

This example compares the pixel information between a Processing PImage and OpenCV Mat of the same external image file. The dimension of the image in Processing is width x height (x, y) while for OpenCV, it is rows() x cols() (y, x). A random point is picked and its pixel color is shown both in Processing PImage and OpenCV Mat.

In Processing

color c1 = img.get(x, y);

In OpenCV

double [] c2 = mat.get(y, x);

We can also observe that the color arrangement in Processing is ARGB and OpenCV is BGR.

The codes are:

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
 
PImage img;
Mat mat;
Mat alpha;
 
void setup() {
  size(640, 480);
  background(0);
  println(Core.VERSION);
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  img = loadImage("sample01.jpg");
  mat = Imgcodecs.imread(dataPath("sample01.jpg"));
  println("PImage size:   " + img.width + "x" + img.height);
  println("Mat size:      " + mat.cols() + "x" + mat.rows());
  println("PImage format: " + img.format);
  println("Mat type:      " + mat.type());
  noLoop();
}
 
void draw() {
  image(img, 0, 0);
  int x = floor(random(img.width));
  int y = floor(random(img.height));
  color c1 = img.get(x, y);
  double [] c2 = mat.get(y, x);
  println("PImage color: " + red(c1) + "," + green(c1) + "," + blue(c1));
  println("Mat color:    " + c2[0] + "," + c2[1] + "," + c2[2]);
}

The console output will be:

3.0.0-rc1
PImage size:   640x480
Mat size:      640x480
PImage format: 1
Mat type:      16
PImage color: 177.0,184.0,203.0
Mat color:    203.0,184.0,177.0