angelustt
angelustt

Reputation: 109

Index out of bounds / IndexError

I am trying to move a kernel around an array of an image to create a gaussian filter. I am getting an IndexError, and Idk why. This is the code: error at line 34

import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen_nueva = np.empty((1931, 1282))

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant', 
constant_values=0)

(dim_x,dim_y)=np.shape(imagen_real)
print((dim_x,dim_y))

ker1 = np.array([[1/16, 1/8, 1/16],
            [1/8, 1/4, 1/8],
            [1/16, 1/8, 1/16]])

def multiplicar_entero():
    global imagen_nueva
    for i in range(1,dim_x+1):
    for j in range(1,dim_y+1):
        matriz_elemento = np.array([[imagen_real[i + 1, j - 1], 
imagen_real[i + 1, j], imagen_real[i + 1, j - 1]],
                        [imagen_real[i, j - 1], imagen_real[i, j], 
imagen_real[i, j + 1]],
                        [imagen_real[i - 1, j - 1], imagen_real[i - 1, j], 
imagen_real[i - 1, j + 1]]])
        valor = np.sum(matriz_elemento*ker1)
        imagen_real[i, j] = valor
        imagen_nueva = np.append(imagen[i, j], (1931, 1282))

As for the confusing matrix with is, and js. It is the matrix 3x3 of each element of the array. I know it may not be the best way of doing it

Upvotes: 0

Views: 268

Answers (1)

Jonas Adler
Jonas Adler

Reputation: 10769

With some minor modifications to your code, such as fixing indentation and using an open source image i do not get any error. So it seems like an indentation errror.

See working code below:

import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen_nueva = np.empty((1931, 1282))

imagen = scipy.resize(misc.ascent(), (1931, 1282))

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant',
                        constant_values=0)

(dim_x, dim_y) = np.shape(imagen_real)
print((dim_x, dim_y))

ker1 = np.array([[1/16, 1/8, 1/16],
                 [1/8, 1/4, 1/8],
                 [1/16, 1/8, 1/16]])


def multiplicar_entero():
    global imagen_nueva
    for i in range(1, dim_x + 1):
        for j in range(1, dim_y + 1):
            matriz_elemento = np.array([[imagen_real[i + 1, j - 1], imagen_real[i + 1, j], imagen_real[i + 1, j - 1]],
                                        [imagen_real[i, j - 1], imagen_real[i, j], imagen_real[i, j + 1]],
                                        [imagen_real[i - 1, j - 1], imagen_real[i - 1, j], imagen_real[i - 1, j + 1]]])

            valor = np.sum(matriz_elemento*ker1)
            imagen_real[i, j] = valor
            imagen_nueva = np.append(imagen[i, j], (1931, 1282))

Upvotes: 1

Related Questions