Skip to content

Instantly share code, notes, and snippets.

@otmb
Last active December 18, 2018 10:17
Show Gist options
  • Save otmb/014107e7b6c6d6a79f0ac1ccc456580a to your computer and use it in GitHub Desktop.
Save otmb/014107e7b6c6d6a79f0ac1ccc456580a to your computer and use it in GitHub Desktop.
Create maximum_filter in OpenCV style

Reference to scipy.ndimage.maximum_filter

Create maximum_filter in OpenCV style

Environment

swift:ViewController.swift

var data : [Double] = [
     0.1,0.1,0.1,0.1,0.1
    ,0.1,0.1,0.1,0.1,0.1
    ,0.1,0.1,0.5,0.1,0.1
    ,0.1,0.1,0.1,0.1,0.1
    ,0.1,0.1,0.1,0.1,0.1
]

let openCV = OpenCVWrapper()
openCV.maximum_filter(
    &data,
    data_size: Int32(data.count),
    data_rows: 5,
    mask_size: 3)

print(data)

[your-project-name]-Bridging-Header.h

#import "OpenCVWrapper.h"

cpp:OpenCVWrapper.h

-(void) maximum_filter: (double *) data
            data_size:(int)data_size
               data_rows:(int)data_rows
                   mask_size:(int)mask_size;

cpp:OpenCVWrapper.mm

#import <opencv2/opencv.hpp>
#import "OpenCVWrapper.h"

using namespace std;

@implementation OpenCVWrapper
-(void) maximum_filter: (double *) data
        data_size:(int)data_size
        data_rows:(int)data_rows
        mask_size:(int)mask_size
{

    std::vector<double> vec(&data[0], data + data_size);
    cv::Mat m1(vec);
    m1 = m1.reshape(0,data_rows);
    cout << "m1 = " << m1 << endl;
    
    cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT,
                                               cv::Size(mask_size,mask_size),
                                               cv::Point(-1,-1));
    cv::Mat d1;
    cv::dilate(m1, d1, kernel);
        
    cout << "d1 = " << d1 << endl;
    int size = d1.rows*d1.cols*sizeof(double);
    std::memcpy(&data[0],d1.data, size);

    // release
    vector<double>().swap(vec);
    m1.release();
    d1.release();
    kernel.release();
}
@end

Result

m1 = [0.1, 0.1, 0.1, 0.1, 0.1;
 0.1, 0.1, 0.1, 0.1, 0.1;
 0.1, 0.1, 0.5, 0.1, 0.1;
 0.1, 0.1, 0.1, 0.1, 0.1;
 0.1, 0.1, 0.1, 0.1, 0.1]
d1 = [0.1, 0.1, 0.1, 0.1, 0.1;
 0.1, 0.5, 0.5, 0.5, 0.1;
 0.1, 0.5, 0.5, 0.5, 0.1;
 0.1, 0.5, 0.5, 0.5, 0.1;
 0.1, 0.1, 0.1, 0.1, 0.1]

## Swift Output
[0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.5, 0.5, 0.5, 0.10000000000000001, 0.10000000000000001, 0.5, 0.5, 0.5, 0.10000000000000001, 0.10000000000000001, 0.5, 0.5, 0.5, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 0.10000000000000001]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment