1

i need to manipulate an numpy array:

My Array has the followng format:

x = [1280][720][4]

The array stores image data in the third dimension:

x[0][0] = [Red,Green,Blue,Alpha]

Now i need to manipulate my array to the following form:

x = [1280][720]
x[0][0] = Red + Green + Blue / 3 

My current code is extremly slow and i want to use the numpy array manipulation to speed it up:

for a in range(0,719):
    for b in range(0,1279):
        newx[a][b] = x[a][b][0]+x[a][b][1]+x[a][b][2]
x = newx            

Also, if possible i need the code to work for variable array sizes.

Thansk Alot

2 Answers 2

1

Use the numpy.mean function:

import numpy as np

n = 1280
m = 720

# Generate a n * m * 4 matrix with random values 
x = np.round(np.random.rand(n, m, 4)*10)

# Calculate the mean value over the first 3 values along the 2nd axix (starting from 0) 
xnew = np.mean(x[:, :, 0:3], axis=2)
  • x[:, :, 0:3] gives you the first 3 values in the 3rd dimension, see: numpy indexing

  • axis=2 specifies, along which axis of the matrix the mean value is calculated.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help, is there a way to keep my 3 dimensions. So xnew[0][0]=[x] ?
Use: xnew_3 = x[:, :, 0:3]
Sorry if I was unclear, I ment to store the mean value in the third dimension. x[1280,720,1] @bastelflp
Resize the first array and overwrite the 3rd dimension with the mean values: xnew_3 = np.resize(x, (x.shape[0], x.shape[1], 1)) and xnew_3[:, :, 0] = xnew
0

Slice the alpha channel out of the array, and then sum the array along the RGB axis and divide by 3:

x = x[:,:,:-1]
x_sum = x.sum(axis=2)
x_div = x_sum / float(3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.