我编写了一段代码,其中我使用 boost::multi_array 在 C++ 中有一个巨大的 3D 矩阵。
对于每个矩阵元素,我想总结一定距离 dist 的邻域。每个元素都根据其到中心的距离进行加权。中心元素不应包含在总和中。
距离 dist 由用户给出并且可以变化。我的程序进行了正确的计算,但是当矩阵变大时速度很慢。我有时有超过 100000 个元素的矩阵......
所以我的问题是:有什么方法可以让这个计算更快?也许也可以使用另一个库?
该部分主要由两个功能组成。在第一个函数中,我访问每个矩阵元素并计算邻域的总和。inputMatrix 是一个 3D boost 多数组:
boost::multi_array<float, 3> inputMatrix = imageMatrix;
T actualElement;
int posActualElement;
for (int depth = 0; depth<inputMatrix.shape()[2]; depth++) {
for (int row = 0; row<inputMatrix.shape()[0]; row++) {
for (int col = 0; col<inputMatrix.shape()[1]; col++) {
indexOfElement[0] = row;
indexOfElement[1] = col;
indexOfElement[2] = depth;
//get actual Element if it is the centre of a whole neighborhood
actualElement = inputMatrix[row][col][depth];
if (!std::isnan(actualElement)) {
//get the sum of the actual neighborhood
sumOfActualNeighborhood = getNeighborhood3D(inputMatrix, indexOfElement);
}
}
}
}
函数neighborhood3D 如下所示:
template <class T, size_t R>
T NGTDMFeatures3D<T, R>::getNeighborhood3D(boost::multi_array<T, R> inputMatrix, int *indexOfElement) {
std::vector<T> neighborhood;
T actElement;
float weight;
for (int k = -dist; k<dist + 1; k++) {
for (int i = -dist; i<dist + 1; i++) {
for (int j = -dist; j<dist + 1; j++) {
if (i != 0 || j != 0 || k != 0) {
if (indexOfElement[0] + i>-1 && indexOfElement[0] + i<inputMatrix.shape()[0] && indexOfElement[1] + j>-1 && indexOfElement[1] + j<inputMatrix.shape()[1] && indexOfElement[2] + k>-1 && indexOfElement[2] + k<inputMatrix.shape()[2]) {
actElement = inputMatrix[indexOfElement[0] + i][indexOfElement[1] + j][indexOfElement[2] + k];
if (!std::isnan(actElement)) {
weight = calculateWeight3D(i, j, k, normNGTDM, actualSpacing);
neighborhood.push_back(weight*actElement);
}
}
}
}
}
}
T sum = accumulate(neighborhood.begin(), neighborhood.end(), 0);
sum = sum / neighborhood.size();
return sum;
}