接着OpenCV的resize函数优化写,对于输入输出图像大小已知,且通道数相同的resize操作,可以使用查表的方法来进行优化,先生成输出图像中每个点对应原图的位置,然后拷贝原图像素点到目标图像。
这里的拷贝操作,也可以换成最邻近、插值等。
创建表
int createTable(int *table, int width_in, int height_in, int channels, int width_out, int height_out){
float step_x = float(width_in)/float(width_out);
float step_y = float(height_in)/float(height_out);
int length = width_out * height_out;
int loc_y = 0;
int loc_x = 0;
int bytes_per_line = width_in * channels;
for (int i = 0; i < length; i++) {
loc_y = i/width_out;
loc_x = i%width_out;
table[i] = int(step_y*loc_y) * bytes_per_line + int(loc_x*step_x)*channels;
}
return 0;
}
resize
void resizeByTable(uchar *input, int channels, int length, int *table, uchar *output){
int mass = 4*(length/4);
for (int i = 0; i < mass; i+=4) {
memcpy(output+(i+0)*3, input+table[i+0], channels);
memcpy(output+(i+1)*3, input+table[i+1], channels);
memcpy(output+(i+2)*3, input+table[i+2], channels);
memcpy(output+(i+3)*3, input+table[i+3], channels);
}
for (int j = mass; j < length; j++) {
memcpy(output+j*3, input+table[j], channels);
}
return;
}
当然resize函数很多可以优化的方法,查表方法是比较暴力的一种方法,对于纹理细节丰富的图像进行resize,在我的mac(2.6 GHz Intel Core i5)上操作1080的图像相比OpenCV有接近4-5倍的速度提升,希望有更好的方法来完善resize操作。