我正在迭代一个 3 维数组(这是一个每个像素有 3 个值的图像),以将 3x3 过滤器应用于每个像素,如下所示:
//For each value on the image
for (i=0;i<3*width*height;i++){
//For each filter value
for (j=0;j<9;j++){
if (notOutsideEdgesCondition){
*(**(outArray)+i)+= *(**(pixelArray)+i-1+(j%3)) * (*(filter+j));
}
}
}
我使用指针算术,因为如果我使用数组表示法,我将有 4 个循环我正在尝试尽可能减少循环次数。我的问题是我的 notOutsideEdgesCondition
已经完全失控了,因为我必须考虑 8 个边界情况。我有以下处理条件
- 左列:
((i%width)==0) &&
(j%3==0)
- 右栏:
((i-1)%width ==0) && (i>1) &&
(j%3==2)
- 上行:
(i
- 下排:
(i>(宽度*高度-宽度)) && (j>5)
并且仍然必须考虑 4 个极端情况,它们将具有更长的表达式。此时我停下来问自己这是否是最好的方法,因为如果我有一个 5 行长的条件评估,它不仅调试起来非常痛苦,而且会减慢内部循环的速度。这就是为什么我来找你询问是否有已知的算法来处理这种情况,或者是否有更好的方法来解决我的问题。多谢。
I'm iterating over a 3 dimensional array (which is an image with 3 values for each pixel) to apply a 3x3 filter to each pixel as follows:
//For each value on the image
for (i=0;i<3*width*height;i++){
//For each filter value
for (j=0;j<9;j++){
if (notOutsideEdgesCondition){
*(**(outArray)+i)+= *(**(pixelArray)+i-1+(j%3)) * (*(filter+j));
}
}
}
I'm using pointer arithmetic because if I used array notation I'd have 4 loops and I'm trying to have the least possible number of loops. My problem is my notOutsideEdgesCondition
is getting quite out of hands because I have to consider 8 border cases. I have the following handled conditions
- Left Column:
((i%width)==0) &&
(j%3==0)
- Right Column:
((i-1)%width ==0) && (i>1) &&
(j%3==2)
- Upper Row:
(i<width) &&
(j<2)
- Lower Row:
(i>(width*height-width)) && (j>5)
and still have to consider the 4 corner cases which will have longer expressions. At this point I've stopped and asked myself if this is the best way to go because If I have a 5 line long conditional evaluation it'll not only be truly painful to debug but will slow the inner loop. That's why I come to you to ask if there's a known algorithm to handle this cases or if there's a better approach for my problem. Thanks a lot.
发布评论
评论(2)
是的,还有更好的方法。编写一个快速循环来处理保证不存在边界问题的情况。这将由从第二个到倒数第二列和倒数第二个到倒数第二行的区域组成。然后,您可以编写四个例程来处理每一侧(第 0 行、第 0 列、第 N 行和第 N 列),并且可以手动编写最后四个点的代码。
也就是说,还有很多更快的方法来进行您正在进行的寻址计算。
Yes, there's a much better way. Write a fast loop to handle the cases where there is guaranteed to be no boundary problems. This will consist of the region from the second to the next-to-last columns and the second to next-to-last rows. Then you can write four routines to handle each of the sides (row 0, column 0, row N and column N) and you can hand code the last four points.
That said, there are also a heck of a lot faster ways of doing the addressing calculations you're doing.
一个不错的提示是在数组的顶部添加一行,在末尾添加另一行(对列执行相同的操作)。
这些附加行/列不会包含任何信息,但它们将简化计算(无边界情况)。以消耗更多内存为代价......
只是一个想法:)
A nice tip is to add an additional row at the top of the array, and another at the end (do the same for the columns).
These additionals rows/columns won't contain any information but they will ease the computation (no border cases). At the price of consuming more memory...
Just an idea :)