Sagen wir, dass ich wünscheIst es möglich, eine Funktion zu vektorisieren, die auf verschiedene Elemente in einem numpy Array zugreift?
den folgenden Code in Python implementierenDiese Funktion ein Bild als 1-dimensionales Array annimmt, und iteriert über einzelne Elemente in der Anordnung (Pixel in dem Eingangsbild), die eine Ausgangsanordnung betrifft, die ist auch ein Bild als ein 1-dimensionales Array dargestellt
Beispiel: ein einzelnes Pixel in dem Eingangsbild (rot) 8 umgebenden Pixeln in (orange) wirkt
eine grundlegende Implementierung in C ist
/* 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 */
}
}
}
würde die naive Ansatz in Python, die genau das gleiche Element weise Zugang zu verwenden, wie unten
#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
gezeigt gibt es einen besseren Weg, dies zu implementieren? Ist es möglich, diese Funktion zu vektorisieren?