gpt4 book ai didi

c++ - 在 C++ 中使用指针加速访问数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:06 24 4
gpt4 key购买 nike

我正在尝试制作一个快速图像阈值函数。目前我做的是:

void threshold(const cv::Mat &input, cv::Mat &output, uchar threshold) {

int rows = input.rows;
int cols = input.cols;

// cv::Mat for result
output.create(rows, cols, CV_8U);

if(input.isContinuous()) { //we have to make sure that we are dealing with a continues memory chunk

const uchar* p;

for (int r = 0; r < rows; ++r) {

p = input.ptr<uchar>(r);

for (int c = 0; c < cols; ++c) {

if(p[c] >= threshold)
//how to access output faster??
output.at<uchar>(r,c) = 255;
else
output.at<uchar>(r,c) = 0;
}
}
}
}

我知道 at() 函数很慢。我怎样才能更快地设置输出,或者换句话说,如何将我从输入获得的指针与输出相关联?

最佳答案

你在想at因为 C++ 标准库为一些容器记录了它,执行范围检查并在超出范围时抛出,但这不是标准库而是 OpenCV。

根据cv::Mat::at文档:

The template methods return a reference to the specified array element. For the sake of higher performance, the index range checks are only performed in the Debug configuration.

因此,没有您可能想的那样进行范围检查。

比较 cv::Mat::atcv::Mat::ptr在源代码中我们可以看到它们几乎相同。

所以 cv::Mat::ptr<>(row)

一样贵
return (_Tp*)(data + step.p[0] * y);

同时 cv::Mat::at<>(row, column)和以下一样贵:

return ((_Tp*)(data + step.p[0] * i0))[i1];

你可能想要 cv::Mat::ptr直接而不是调用 cv::Mat::at每列以避免进一步重复 data + step.p[0] * i0 操作,自己执行 [i1]

所以你会这样做:

/* output.create and stuff */

const uchar* p, o;

for (int r = 0; r < rows; ++r) {

p = input.ptr<uchar>(r);
o = output.ptr<uchar>(r); // <-----

for (int c = 0; c < cols; ++c) {

if(p[c] >= threshold)
o[c] = 255;
else
o[c] = 0;
}
}

作为旁注,您不会也不应该检查 cv::Mat::isContinuous在这里,间隙是从一行到另一行,您将指针指向单行,因此您不需要处理矩阵间隙。

关于c++ - 在 C++ 中使用指针加速访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30247418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com