高效遍历像素注意事项:
1、at方法在需要随机访问像素的时候使用,绝不要在扫描图像时使用;
2、使用较短的循环和多条语句通常比使用较长的循环和单条语句的运行效率高;
3、针对连续图像生成一个循环而不是行列二重循环;
4、优先使用位运算;
5、对于可以预先计算的数值,要避免在循环中重复计算,提前算好;
6、使用多线程OpenMP、TBB、多线程
void colorReduce(Mat image, int div)
{
#ifndef BIT_OP
// 行数
int nl = image.rows;
// 每行的元素数量
int nc = image.cols * image.channels();
int halfDiv = div >> 1;
for (int i = 0; i < nl; i++) {
// 取得i行的地址
uchar* data = image.ptr<uchar>(i);
for (int j = 0; j < nc; j++) {
data[j] = data[j] / div * div + halfDiv;
}
}
return;
#endif // !BIT_OP
int n1 = image.rows;
int nc = image.cols * image.channels();
if (image.isContinuous()) {
nc = nc * n1;
n1 = 1;
}
int n = static_cast<int>(log(static_cast<double>(div)) / log(2.0) + 0.5);
uchar mask = 0xFF << n;
uchar div2 = div >> 1;
for (int i = 0; i < n1; i++) {
uchar* data = image.ptr<uchar>(i);
for (int j = 0; j < nc; ++j) {
*data &= mask;
*data++ += div2;
}
}
}
网友评论