gidesa / ocvWrapper46

Opencv C++ API wrapper for Delphi, Lazarus/Freepascal and C - for Opencv v 4.6
GNU General Public License v3.0
61 stars 12 forks source link

numpy #14

Closed spambox1964 closed 1 year ago

spambox1964 commented 1 year ago

Here is a Python code snippet that uses the numpy library. Is it possible to rewrite it as a Delphi program using the ocvWrapper46 library?

kernel = numpy.array([ [0, -1, 0], [-1, 5, -1], [0, -1, 0] ]) bw = cv.filter2D(bw, -1, kernel)

gidesa commented 1 year ago

yes, for example:

type TArMat = array of array of Integer;

procedure array2mat(ar: TArMat; pmat: PCvMat_t); var i, j, r, c: Integer; begin r:=Length(ar); c:=Length(ar[0]); // create Ocv matrix with type floating point 32 bit pmat:=pCvMat2dCreate(r, c, CV_32FC1); for i:=0 to r-1 do for j:=0 to c-1 do begin pCvMatSetFloat(pmat, i, j, ar[i,j]); end; end;

var arKernel: TArMat; kernel: PCvMat_t;

................................... // fill arKernel with your data, then convert to Ocv mat array2mat(arKernel, kernel); pCvfilter2D(srcImg, dstImg, -1, kernel); // other parameters optional .............. // when done, remember to delete Ocv mat PcvMatDelete(kernel);

source image could be same as destination.

spambox1964 commented 1 year ago

Great! I have rewritten the Python code into the following Delphi code and successfully obtained the desired result:

  SetLength(arKernel, 3);
  arKernel[0]:=[0,-1,0];
  arKernel[1]:=[-1,5,-1];
  arKernel[2]:=[0,-1,0];
  array2mat(arKernel, kernel);

By the way, it should be declared in the following way for array2mat to be correct:

procedure array2mat(ar: TArMat; var pmat: PCvMat_t);

Thank you very much.

gidesa commented 1 year ago

Yes, "var" was missing in procedure signature. In modern versions of Delphi you could initialize the array in compact mode (but only for global variables):

var arKernel: TArMat {or directly: array of array of integer}= [[0, -1, 0], [-1, 5, -1], [0, -1, 0]];