如果满足某些条件,是否有一种简单的方法将cv :: Mat中的所有值设置为给定值。例如,我有一个CV_32FC1矩阵,并且我想将所有值为0的值设置为20。在MATLAB中,我会这样做:
M(M == 0) = 20;
你可以使用
cv::Mat mask = M == 0;
M.setTo(0.5, mask);
然而,这种方法需要使用额外的内存来创建掩码,但由于使用了opencv API,因此可以应用于所有矩阵类型。如果考虑性能问题,您可以直接参考Mat::data,以针对具体的矩阵类型对该解决方案进行优化。
感谢@marol的评论,我采用了下面的实现。我使用C++11 lambda函数来条件判断哪些值需要更改。为了展示其威力,我的条件是当值超出范围[MIN_VAL
, MAX_VAL
]时设置为DEFAULT_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);
.
.
.
}
cv::Mat newMask = mask <= 2;
但这个不行:cv::Mat newMask = mask > 2 && mask < 5;
- David Doria(mask > 2) & (mask < 5)
。 - rob3c