Optimize iteration through numpy array

I am exchanging the values ​​of a multidimensional numpy array in Python. But the code is too slow. Another thread says:

As a rule, you avoid iterating through them directly .... there is a good chance that it is easy to vectorize.

So, do you know a way to optimize the following code?

import PIL.Image import numpy pil_image = PIL.Image.open('Image.jpg').convert('RGB') cv_image = numpy.array(pil_image) # Convert RGB to BGR for y in range(len(cv_image)): for x in range(len(cv_image[y])): (cv_image[y][x][0], cv_image[y][x][2]) = (cv_image[y][x][2], cv_image[y][x][0]) 

For a 509x359 image, this is the last of more than one second, which is too much. He must complete this task as soon as possible.

+4
source share
1 answer

How about this one operation that inverts the matrix along the last axis?

 cv_image = cv_image[:,:,::-1] 
+5
source

All Articles