vendredi 3 avril 2026

Using Filter2D with Rebol-OpenCV

 Rebol-OpenCV (https://github.com/Oldes/Rebol-OpenCV) Filter2D is really fantastic for creating various filters on image.

filter2D: [
"Convolves an image with the kernel."
src    [handle!] "cvMat"
dst    [handle! none!] "cvMat"
ddepth [integer!] "desired depth of the destination image"
kernel [handle!] "convolution kernel (or rather a correlation kernel), a single-channel floating point matrix"
anchor [pair! integer!] "position of the anchor within the element"
delta  [number!] "value added to the filtered pixels before storing them in dst"
/border "border mode used to extrapolate pixels outside of the image"
type [integer!] "one of: [0 1 2 4 5 16]"
]

This is an example of creating a Kuwahara_filter

#!/usr/local/bin/r3
Rebol [
]
;--https://en.wikipedia.org/wiki/Kuwahara_filter
cv: import opencv
with cv [
    src: imread/with "../images/mandrill.jpg" -1 ;--(IMREAD_UNCHANGED)
    dst: Matrix :src ;--create a matrix
    ;--using Rebol vector type for a 3x3 kernel
    vec: #(f32! [-0.5 1.5 -0.5 1.5 -3.0 1.5 -0.5 1.5 -0.5]) ;--sum = 1
    filter: Matrix [CV_32FC1 3x3 :vec] ;--a 3x3 kernel
    filter2D :src :dst -1 :filter -1x1 0 ;-1 same image depth
    ;--show result
    imshow/name src "Source"
    imshow/name dst "Kuwahara"
    moveWindow "Source"  0x0
    moveWindow "Kuwahara" 260x0
    waitKey 0
    destroyAllWindows

]

The trick is to use vector datatype implemented by Oldes to create the kernel used by the filter2D function.
The result for the Kuwahara_filter:


You can find here https://github.com/ldci/R3_OpenCV_Samples/tree/main/image_filtering a lot of examples for generating filters on image.