'Invalid index to scalar variable: copying entries from one np array to another np array element-wise
For context, I am writing code to compute the gray-level co-occurrence matrix in python for my data mining assignment.
when I have
c = np.array([[1,1,2,1,3],
[2,1,2,3,3],
[1,2,1,1,3],
[1,3,1,2,1],
[3,3,2,1,1]])
and call glcm(c, 3, 2, 1) it matches with what the example we went over in class and no errors occur. I have the function call within the same cell as the function definition in Jupyter notebook. When I call the function on an image matrix (np array), I get an error saying invalid index to scalar variable on the line specified in the code below.
I find this weird because it works with the example (np-array named c) but does not work on other np arrays that represent grayscale images.
Am I populating C_shift incorrectly?
def glcm(C, k, mu, nu):
C_rows = c.shape[0]
C_cols = c.shape[1]
C_shift = np.zeros((C_rows, C_cols))
C_shift[:] = np.nan # initialize everything to NaN
# calculate C_shift
for i in range(C_rows - mu):
for j in range(C_cols - nu):
C_shift[i][j] = C[i+mu][j+nu] # ERROR: invalid index to scalar variable.
# set the values of g
g = np.zeros((k,k))
for i in range(k):
Ii = mat_map(C,i+1)
for j in range(k):
Ij = mat_map(C_shift, j+1)
g[i][j] = np.multiply(Ii, Ij).sum()
return g, g.sum()
Solution 1:[1]
EDIT:
I resolved it, turns out that I was not actually inputting a 2d array and was inputting a flattened array.
The array named 'c' above was what I thought I was inputting but I was actually inputting a flattened array (aka a vector). That is why when I try calling C[i+mu][j+nu] I was getting the invalid index to scalar variable because when C[i+mu] is called it would just return the i+mu'th number in the array. You cannot get the j+nu'th number of a scalar which is why the error occurred.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
