Tim Heß
Tim Heß

Reputation: 17

Python numpy array manipulation

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

Upvotes: 1

Views: 211

Answers (2)

Brian Huey
Brian Huey

Reputation: 1630

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)

Upvotes: 0

bastelflp
bastelflp

Reputation: 10126

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.

Upvotes: 1

Related Questions