다음 코드를 파이썬으로 구현하고자한다고 가정 해 봅시다.numpy 배열에서 다른 요소에 액세스하는 함수를 벡터화 할 수 있습니까?
이 함수는 이미지를 1 차원 배열로 가져 와서 출력 배열에 영향을주는 배열의 개별 요소 (입력 이미지의 픽셀)를 반복합니다. 또한, 화상은 1 차원 배열로 표현
예 : 입력 화상 (적색)의 단일 화소 (오렌지)의 8 개의 주변 화소에 영향을 는
C의 기본 구현은
,745 인/* 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 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
아래 그림과 같이 정확히 같은 요소 현명한 접근을 사용하는 것입니다? 이 함수를 벡터화 할 수 있습니까?