gpt4 book ai didi

c++ - 同时重新排序和旋转图像的高效方法

转载 作者:太空狗 更新时间:2023-10-29 21:39:51 24 4
gpt4 key购买 nike

为了快速加载 jpeg,我为 turbojpeg 实现了一个 .mex-wrapper 以有效地将(大)jpeg 读入 MATLAB。对于 4000x3000 像素的图像,实际解码只需要大约 120 毫秒(而不是 5 毫秒)。然而,像素排序是 RGBRGBRGB... ,而 MATLAB 需要一个 [W x H x 3] 矩阵,它在内存中是一个 W*H*3 数组,其中第一个 WH 条目对应于红色,第二个 WH 条目对应于绿色,最后一个 WH 条目为蓝色。此外,图像从左上角到右下角围绕轴进行镜像。

重排循环的直接实现如下:

// buffer contains mirrored and scrambled output of turbojpe
// outImg contains image matrix for use in MATLAB
// imgSize is an array containing {H,W,3}
for(int j=0; j<imgSize[1]; j++) {
for(int i=0; i<imgSize[0]; i++) {
curIdx = j*imgSize[0] + i;
curBufIdx = (i*imgSize[1] + j)*3;
outImg[curIdx] = buffer[curBufIdx++];
outImg[curIdx + imgSize[0]*imgSize[1] ] = buffer[curBufIdx++];
outImg[curIdx + 2*imgSize[0]*imgSize[1] ] = buffer[curBufIdx];
}
}

它可以工作,但大约需要 120 毫秒(而不是 20 毫秒),大约与实际解码一样长。关于如何使此代码更高效的任何建议?

由于错误,我更新了处理时间。

最佳答案

编辑: 99% 的 C 库将按行优先存储图像,这意味着如果您从 turbojpeg 获得 3 x WH(二维数组),您可以将其视为 3 x W x H(上面的预期输入)。在此表示中,像素先横向读取,然后向下读取。您需要他们在 MATLAB 中先阅读再阅读。您还需要将像素顺序 (RGBRGBRGB...) 转换为平面顺序 (RRRR....GGGGG....BBBBB...)。解决方案是 permute(reshape(I,3,W,H),[3 2 1])


这是其中一种情况,其中 MATLAB 的 permute命令可能会比您在短时间内手工编写的任何代码都快(至少比所示循环快 50%)。我通常避开使用 mexCallMATLAB 的解决方案,但我认为这可能是一个异常(exception)。但是,输入是 mxArray,这可能会带来不便。无论如何,下面是如何执行 permute(I,[3 2 1]):

#include "mex.h"

int computePixelCtoPlanarMATLAB(mxArray*& imgPermuted, const mxArray* img)
{
mxArray *permuteRHSArgs[2];
// img must be row-major (across first), pixel order (RGBRGBRGB...)
permuteRHSArgs[0] = const_cast<mxArray*>(img);
permuteRHSArgs[1] = mxCreateDoubleMatrix(1,3,mxREAL);

// output is col-major, planar order (rows x cols x 3)
double *p = mxGetPr(permuteRHSArgs[1]);
p[0] = 3;
p[1] = 2;
p[2] = 1;

return mexCallMATLAB(1, &imgPermuted, 2, permuteRHSArgs, "permute");
}

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
// do some argument checking first (not shown)
// ...

computePixelCtoPlanarMATLAB(plhs[0], prhs[0]);
}

或者在 MATLAB 中自己调用 permute(I,[3 2 1])

首先从 3xWH 变为 3xWxH 的 reshape 怎么样?只要告诉代码,它真的是 3xWxH! reshape 不移动数据 - 它只是告诉 MATLAB 将给定的数据缓冲区视为特定大小。

关于c++ - 同时重新排序和旋转图像的高效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32059654/

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