【发布时间】:2016-10-16 07:40:04
【问题描述】:
假设我希望在 python 中实现以下代码
此函数将图像作为一维数组,并迭代数组中的各个元素(输入图像中的像素),这会影响输出数组,该输出数组也是表示为一维数组的图像
示例: 输入图像(红色)中的单个像素会影响(橙色)中的 8 个周围像素
C 中的基本实现是
/* C version
* Given an input image create an
* output image that is shaped by individual pixels
* of the input image
*/
int image[width * height]; //image retrieved elsewhere
int output [width * height]; //output image
int y = 0, x = 0;
for( y = 1; y < height-1 ; ++ y) {
for(x = 1; x < width-1; ++ x) {
if (image[y * width + x] > condition) {
/* pixel affects the surrounding 8 pixels in the output image */
output[(y-1) * width + x - 1]++; /* upper left */
output[(y-1) * width + x ]++; /* above */
output[(y-1) * width + x + 1]++; /* upper right */
output[y * width + x + 1 ]++; /* right */
output[y * width + x - 1 ]++; /* left */
output[(y+1) * width + x - 1]++; /* lower left */
output[(y+1) * width + x ]++; /* below */
output[(y+1) * width + x + 1]++; /* lower right */
}
}
}
python 中的幼稚方法是使用完全相同的元素明智访问,如下所示
#Python version
input = blah # formed elsewhere
output = np.zeros(width * height)
for y in xrange(1, height-1):
for x in xrange(1, width-1):
if input[y * width + x] > condition:
output[(y-1) * width + x - 1]+= 1; # upper left
output[(y-1) * width + x ]+= 1; # above
output[(y-1) * width + x + 1]+= 1; # upper right
output[y * width + x + 1 ]+= 1; # right
output[y * width + x - 1 ]+= 1; # left
output[(y+1) * width + x - 1]+= 1; # lower left
output[(y+1) * width + x ]+= 1; # below
output[(y+1) * width + x + 1]+= 1; # lower right
有没有更好的方法来实现这个?是否可以对这个函数进行矢量化?
【问题讨论】:
标签: python arrays numpy vectorization