Skip to content
This repository has been archived by the owner on Jan 25, 2022. It is now read-only.

Gotchas

Amro edited this page Nov 18, 2017 · 4 revisions

Gotchas and Common Mistakes

0-based vs. 1-based indexing

C++/OpenCV uses 0-based indexing while MATLAB uses 1-based indexing. That is, the top left pixel is (0,0) in OpenCV whereas MATLAB treats it as (1,1). mexopencv does NOT automatically convert image coordinates. Be careful when accessing a function that deals with image coordinates.

This also applies to functions that deal with indices (meaning that indices in OpenCV functions are expected to be 0-based).

Channeled arrays

OpenCV often uses channels as dimensions of coordinate representation, as seen in cv.perspectiveTransform. In MATLAB, you can make such channeled array by creating 1xNxd or Nx1xd array for an N-element array of d-dimensional vectors.

Hint: use permute or shiftdim functions to convert from/to Nxd numeric array in MATLAB.

BGR vs. RGB color format

OpenCV internally represents color images in BGR order, while MATLAB uses RGB order. You can easily flip color channel in MATLAB using the flip function as: bgr = flip(rgb,3) or vice versa.

Particularly image/video IO functions (but not limited to those):

  • cv.imread, cv.imreadmulti, cv.imdecode, cv.VideoCapture: OpenCV returns a BGR output image
  • cv.imwrite, cv.imencode, cv.VideoWriter: OpenCV takes a BGR input image

An option 'FlipChannels' is offered in some functions which takes into account the BGR/RGB difference (by default turned on for the above IO functions).

The pixel format difference also applies to OpenCV drawing functions that accept some kind of 'Color' argument (e.g cv.line). For convenience, colors in such drawing functions can also be specified using MATLAB short-name ColorSpec convention (i.e 'r', 'g', 'b', 'c', 'm', 'y', 'k', or 'w').