I am trying to write OpenCV FFI in Racket and arrived at the point where arrays should be managed efficiently. However, all my attempts to access arrays using Racket FFI have led to very inefficient code. Is there a way to quickly access C arrays using FFI?
In Racket, this type of manipulation is fast enough, that is:
(define a-vector (make-vector (* 640 480 3)))
(time (let loop ([i (- (* 640 480 3) 1)])
(when (>= i 0)
;; invert each pixel channel-wise
(vector-set! a-vector i (- 255 (vector-ref a-vector i)))
(loop (- i 1)))))
-> cpu time: 14 real time: 14 gc time: 0
Now in OpenCV there is a structure with a name IplImagethat looks like this:
typedef struct _IplImage
{
int imageSize;
...
char *imageData;
}IplImage;
The structure is defined in Racket as follows:
(define-cstruct _IplImage
([imageSize _int]
...
[imageData _pointer]))
Now we load the image using the function cvLoadImageas follows:
(define img
(ptr-ref
(cvLoadImage "images/test-image.png" CV_LOAD_IMAGE_COLOR)
_IplImage))
The pointer imageDatacan be accessed:(define data (IplImage-imageData img)))
data, , , :
(time (let loop ([i (- (* width height channels) 1)]) ;; same 640 480 3
(when (>= i 0)
;; invert each pixel channel-wise
(ptr-set! data _ubyte i (- 255 (ptr-ref data _ubyte i)))
(loop (- i 1)))))
-> cpu time: 114 real time: 113 gc time: 0
, Racket.
, _array, _cvector, , C, . C Racket FFI. Racket . , , OpenCV Racket.
?