您可能想查看compare。例子:
//Mat mask; compare(src, 10.0, mask, CMP_LT);
Mat mask = src < 10.0;
根据您希望执行的实际操作,您可以使用比较的结果,否则您可以查看gpu 模块。特别是每个元素的操作。
就我个人而言,我觉得 OpenCV 应该有点像 MATLAB,避免循环,使用矩阵,并尽可能尝试使用内置函数(即使它们只是作为循环实现,它可以节省你再次输入相同的东西然后再次)。
编辑:以下是使用循环和使用内置矩阵运算符来完成更新问题中的任务的示例代码:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//#include <opencv2/gpu/gpu.hpp>
using namespace cv;
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
// Load Image
Mat matImage = imread("Test.png");
// Convert to Grayscale
Mat matGray(matImage.rows, matImage.cols, CV_8UC1);
cvtColor(matImage, matGray, CV_BGR2GRAY);
double time, dThreshold = 50.0;
//int TIMES = 1000;
//namedWindow("Display", WINDOW_NORMAL);
//char chKey;
//imshow("Display", matGray);
//chKey = '\0'; while (chKey != '') chKey = waitKey(0);
//----------------------------- Loop Method -------------------------------
time = (double) getTickCount();
//for (int k = 0; k < TIMES; k++)
//{
Mat matLoop = matGray.clone();
for (int i = 0; i < matLoop.rows; ++i)
{
for (int j = 0; j < matLoop.cols; ++j)
{
uchar& unValue = matLoop.at<uchar>(i, j);
if (unValue < dThreshold)
unValue = pow(unValue, 2);
else
unValue--;
}
}
//}
time = 1000*((double)getTickCount() - time)/getTickFrequency();
//time /= TIMES;
cout << "Loop Method Time: " << time << " milliseconds." << endl;
//imshow("Display", matLoop);
//chKey = '\0'; while (chKey != '') chKey = waitKey(0);
//---------------------------- Matrix Method ------------------------------
time = (double) getTickCount();
//for (int i = 0; i < TIMES; i++)
//{
Mat matMask, matMatrix;
matMask = matGray < dThreshold;
bitwise_and(matGray, matMask, matMatrix);
pow(matMatrix, 2.0, matMatrix);
subtract(matGray, 1.0, matMatrix, ~matMask);
//}
time = 1000*((double)getTickCount() - time)/getTickFrequency();
//time /= TIMES;
cout << "Matrix Method Time: " << time << " milliseconds." << endl;
//imshow("Display", matMatrix);
//chKey = '\0'; while (chKey != '') chKey = waitKey(0);
return 0;
}
除了将需要键入的代码行数从 12 行减少到 5 行之外,矩阵方法也更快。启用时序循环(使用TIMES = 1000;
),我得到以下时间用于中等大小的图像:
Loop Method Time: 9.19669 milliseconds.
Matrix Method Time: 2.82657 milliseconds.
使用 gpu 模块,我相信您可以进一步减少第二次,但不幸的是,我目前没有合适的显卡连接到我当前的系统。