优化基本原则:
1.减少多层循环的使用
2.尽量使用位运算
基于以上原则,可将之前几篇博文中介绍的Color Reduce算法代码改为:
voidcolorReduce5(Mat&image, intn=6) {
intnl= image.rows;
intnc= image.cols;
intdiv = (int)pow(2.0f,n);
ucharmask = 0xFF<<n;
if(image.isContinuous())
{
nc=nl*nc;
nl=1;
}
for(int j=0;j<nl;j++)
{
uchar*data= image.ptr<uchar>(j);
for(int i=0;i<nc;i++) {
*data++= *data&mask+ div/2;
*data++= *data&mask+ div/2;
*data++= *data&mask+ div/2;
}
}
}
执行效率测试对比
测试环境:
图像:500*338pixel
CPU:Pentium(R) Dual-Core CPU E5800 3.20GHz
测试结果:
ColorReduce1 | 0.00225389ms |
ColorReduce2 | 0.00215909ms |
ColorReduce3 | 0.00180068ms |
ColorReduce4 |
0.0830474ms
|
ColorReduce5 |
0.00131263ms
|