Thanks to the comments of @marol, I settled on the implementation below. I use C ++ 11 lambda functions to determine which values ββneed to be changed. To demonstrate my power, my condition is to set the DEFAULT_VAL value when the value is out of the range [ MIN_VAL , MAX_VAL ]:
#include <functional> #define MatType float #define MatCmpFunc std::function<bool(const MatType&)> . . . // function which accepts lambda function to condition values which need to // be changed void MatSetIf(cv::Mat& inputmat, const MatType& newval, MatCmpFunc func) { float* pmat = (float*)inputmat.data; // iterate and set only values which fulfill the criteria for (int idx = 0; idx < inputmat.total(); ++idx) { if (func(pmat[idx])) { pmat[idx] = newval; } } } . . . void main() { cv::Mat mymat(100,100,CV_32FC1); const float MIN_VAL = 10; const float MAX_VAL = 1000; const float DEFAULT_VAL = -1; . . . // declare lambda function which returns true when mat value out of range MatCmpFunc func = [&](const DepthMatType& val) -> bool { return (val < MIN_VAL || val > MAX_VAL) ? true : false; }; // use lambda func above to set all out of range values to 50 Mat32FSetIf(mymat, DEFAULT_VAL, func); . . . }
source share