Home > other >  OOP Best Way To Call Similar Functions
OOP Best Way To Call Similar Functions

Time:08-09

Background: I have 2 similar blocks of code that I would like to merge together in a function. One block is for the x axis and the other is for the y axis. I have had this similar issue multiple times before and have shrugged it off since I assumed there was no better way of merging these in a clean fashion.

Problem: How do I make a function that can replace both snippets of code below in the least number of lines?

Code:

    //rows
    vector<float> rowSpectrum;
    float tempVal;
    for (int i = 0; i < ROI.size().height; i  ) {
        tempVal = cv::mean(cleanImg.row(i)).val[0];
        rowSpectrum.push_back(tempVal);
    }

    //columns
    vector<float> colSpectrum;
    for (int i = 0; i < ROI.size().width; i  ) {
        tempVal = cv::mean(cleanImg.col(i)).val[0];
        colSpectrum.push_back(tempVal);
    }

CodePudding user response:

auto calcSpectrum = [&](int size, cv::Mat (cv::Mat::*memFn)(int) const) {
    vector<float> spectrum;
    for (int i = 0; i < size; i  ) {
        auto tempVal = cv::mean((cleanImg.*memFn)(i)).val[0];
        spectrum.push_back(tempVal);
    }
    return spectrum;
}

auto rowSpectrum = calcSpectrum(ROI.size().height, &cv::Mat::row);
auto colSpectrum = calcSpectrum(ROI.size().width, &cv::Mat::col);
  • Related