4

I'm swapping values of a multidimensional numpy array in Python. But the code is too slow. Another thread says:

Typically, you avoid iterating through them directly. ... there's a good chance that it's 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 an 509x359 image this last more than one second, which is way too much. It should perform it's task in no time.

2
  • 2
    on a side note, cv_image[y][x][0] is generally written cv_image[y, x, 0] in numpy/python. Commented Jul 3, 2012 at 19:12
  • Thanks. Now it only lasts 0.406 seconds. Commented Jul 3, 2012 at 19:25

1 Answer 1

5

How about this single operation inverting the matrix along the last axis?

cv_image = cv_image[:,:,::-1]
Sign up to request clarification or add additional context in comments.

4 Comments

There's something strange with this. Both types (source and result) are numpy.ndarray. When iterating through them and comparing len(...) or the values (reversely), there can't be found a difference. But when trying to show the image with cv2.imshow it says: error: (-206) Unrecognized or unsupported array type (while without the conversion the image is displayed [with wrong colors]).
I use the line: new_cv_image = cv_image[:, :, ::-1]. If I change one value in cv_image: cv_image[0, 0, 2] = 128, it is also changed in new_cv_image, although id(...) returns a different value for each.
You could try cv_image = cv_image[..., ::-1].copy(). imshow is probably expecting a continuous array in memory.
@Bago: I came to the same conclusion (source: mbk.ps.uci.edu/python.html , search "copy"). This works perfectly well! I measured 0.0 seconds (no time). I would say: Goal achieved.

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.